blob: c3768b3a7c1038bc86b94882fcdda8b76aa3f29c [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"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000020#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000022
23using namespace clang;
24
25namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000026 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000070 Decl *VisitUsingDecl(UsingDecl *D);
71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000072 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor8dbc2692009-03-17 21:15:40 +000075 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000076 Decl *VisitDecl(Decl *D) {
77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78 Diagnostic::Error,
79 "cannot instantiate %0 yet");
80 SemaRef.Diag(D->getLocation(), DiagID)
81 << D->getDeclKindName();
82
Douglas Gregor8dbc2692009-03-17 21:15:40 +000083 return 0;
84 }
Douglas Gregor5545e162009-03-24 00:38:23 +000085
John McCallfd810b12009-08-14 02:03:10 +000086 const LangOptions &getLangOptions() {
87 return SemaRef.getLangOptions();
88 }
89
Douglas Gregor5545e162009-03-24 00:38:23 +000090 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000091 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000092 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000093 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000094 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000095
96 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000097 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000098
99 bool InstantiateClassTemplatePartialSpecialization(
100 ClassTemplateDecl *ClassTemplate,
101 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 };
103}
104
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000105// FIXME: Is this too simple?
106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
107 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
108 TmplAttr = TmplAttr->getNext()) {
109
110 // FIXME: Is cloning correct for all attributes?
111 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
112
113 New->addAttr(NewAttr);
114 }
115}
116
Douglas Gregor4f722be2009-03-25 15:45:12 +0000117Decl *
118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
119 assert(false && "Translation units cannot be instantiated");
120 return D;
121}
122
123Decl *
124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125 assert(false && "Namespaces cannot be instantiated");
126 return D;
127}
128
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
130 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000131 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000132 if (DI->getType()->isDependentType()) {
133 DI = SemaRef.SubstType(DI, TemplateArgs,
134 D->getLocation(), D->getDeclName());
135 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000137 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 }
139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000141 // Create the new typedef
142 TypedefDecl *Typedef
143 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000144 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 if (Invalid)
146 Typedef->setInvalidDecl();
147
John McCall5126fd02009-12-30 00:31:22 +0000148 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
149 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Prev, TemplateArgs);
150 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
151 }
152
John McCall46460a62010-01-20 21:53:11 +0000153 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000154 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000156 return Typedef;
157}
158
Douglas Gregor6eef5192009-12-14 19:27:10 +0000159/// \brief Instantiate the arguments provided as part of initialization.
160///
161/// \returns true if an error occurred, false otherwise.
162static bool InstantiateInitializationArguments(Sema &SemaRef,
163 Expr **Args, unsigned NumArgs,
164 const MultiLevelTemplateArgumentList &TemplateArgs,
165 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
166 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
167 for (unsigned I = 0; I != NumArgs; ++I) {
168 // When we hit the first defaulted argument, break out of the loop:
169 // we don't pass those default arguments on.
170 if (Args[I]->isDefaultArgument())
171 break;
172
173 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
174 if (Arg.isInvalid())
175 return true;
176
177 Expr *ArgExpr = (Expr *)Arg.get();
178 InitArgs.push_back(Arg.release());
179
180 // FIXME: We're faking all of the comma locations. Do we need them?
181 FakeCommaLocs.push_back(
182 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
183 }
184
185 return false;
186}
187
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000188Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000189 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000190 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000191 TemplateArgs,
192 D->getTypeSpecStartLoc(),
193 D->getDeclName());
194 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 return 0;
196
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000197 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000198 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
199 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000200 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000201 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000202 Var->setThreadSpecified(D->isThreadSpecified());
203 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
204 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
206 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000207 // out-of-line, the instantiation will have the same lexical
208 // context (which will be a namespace scope) as the template.
209 if (D->isOutOfLine())
210 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000211
John McCall46460a62010-01-20 21:53:11 +0000212 Var->setAccess(D->getAccess());
213
Mike Stump390b4cc2009-05-16 07:39:55 +0000214 // FIXME: In theory, we could have a previous declaration for variables that
215 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000216 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000217 // FIXME: having to fake up a LookupResult is dumb.
218 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
219 Sema::LookupOrdinaryName);
220 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Douglas Gregor7caa6822009-07-24 20:34:43 +0000222 if (D->isOutOfLine()) {
223 D->getLexicalDeclContext()->addDecl(Var);
224 Owner->makeDeclVisibleInContext(Var);
225 } else {
226 Owner->addDecl(Var);
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000229 // Link instantiations of static data members back to the template from
230 // which they were instantiated.
231 if (Var->isStaticDataMember())
232 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000233 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000234
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000235 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000236 if (Var->isStaticDataMember() && !D->isOutOfLine())
237 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
238 else
239 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
240
Douglas Gregor6eef5192009-12-14 19:27:10 +0000241 // Extract the initializer, skipping through any temporary-binding
242 // expressions and look at the subexpression as it was written.
243 Expr *DInit = D->getInit();
244 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
245 DInit = Binder->getSubExpr();
246 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
247 DInit = ICE->getSubExprAsWritten();
248
249 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
250 // The initializer is a parenthesized list of expressions that is
251 // type-dependent. Instantiate each of the expressions; we'll be
252 // performing direct initialization with them.
253 llvm::SmallVector<SourceLocation, 4> CommaLocs;
254 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
255 if (!InstantiateInitializationArguments(SemaRef,
256 PLE->getExprs(),
257 PLE->getNumExprs(),
258 TemplateArgs,
259 CommaLocs, InitArgs)) {
260 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000261 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000262 PLE->getLParenLoc(),
263 move_arg(InitArgs),
264 CommaLocs.data(),
265 PLE->getRParenLoc());
266 }
267 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
268 // The initializer resolved to a constructor. Instantiate the constructor
269 // arguments.
270 llvm::SmallVector<SourceLocation, 4> CommaLocs;
271 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
272
273 if (!InstantiateInitializationArguments(SemaRef,
274 Construct->getArgs(),
275 Construct->getNumArgs(),
276 TemplateArgs,
277 CommaLocs, InitArgs)) {
278 if (D->hasCXXDirectInitializer()) {
279 SourceLocation FakeLParenLoc =
280 SemaRef.PP.getLocForEndOfToken(D->getLocation());
281 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
282 : CommaLocs.back();
283 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
284 FakeLParenLoc,
285 move_arg(InitArgs),
286 CommaLocs.data(),
287 FakeRParenLoc);
288 } else if (InitArgs.size() == 1) {
289 Expr *Init = (Expr*)(InitArgs.take()[0]);
290 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
291 SemaRef.Owned(Init),
292 false);
293 } else {
294 assert(InitArgs.size() == 0);
295 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
296 }
297 }
298 } else {
299 OwningExprResult Init
300 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
301
302 // FIXME: Not happy about invalidating decls just because of a bad
303 // initializer, unless it affects the type.
304 if (Init.isInvalid())
305 Var->setInvalidDecl();
306 else
307 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
308 D->hasCXXDirectInitializer());
309 }
310
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000311 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000312 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
313 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000314
315 return Var;
316}
317
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000318Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
319 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000320 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000321 if (DI->getType()->isDependentType()) {
322 DI = SemaRef.SubstType(DI, TemplateArgs,
323 D->getLocation(), D->getDeclName());
324 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000325 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000326 Invalid = true;
327 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 // C++ [temp.arg.type]p3:
329 // If a declaration acquires a function type through a type
330 // dependent on a template-parameter and this causes a
331 // declaration that does not use the syntactic form of a
332 // function declarator to have function type, the program is
333 // ill-formed.
334 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000335 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000336 Invalid = true;
337 }
338 }
339
340 Expr *BitWidth = D->getBitWidth();
341 if (Invalid)
342 BitWidth = 0;
343 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000344 // The bit-width expression is not potentially evaluated.
345 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000347 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000348 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000349 if (InstantiatedBitWidth.isInvalid()) {
350 Invalid = true;
351 BitWidth = 0;
352 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000353 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000354 }
355
John McCall07fb6be2009-10-22 23:33:21 +0000356 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
357 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000359 D->getLocation(),
360 D->isMutable(),
361 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000362 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000363 D->getAccess(),
364 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000365 if (!Field) {
366 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000367 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000370 InstantiateAttrs(D, Field);
371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 if (Invalid)
373 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000375 if (!Field->getDeclName()) {
376 // Keep track of where this decl came from.
377 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378 }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000380 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000381 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000382 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383
384 return Field;
385}
386
John McCall02cace72009-08-28 07:59:38 +0000387Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
388 FriendDecl::FriendUnion FU;
389
390 // Handle friend type expressions by simply substituting template
391 // parameters into the pattern type.
392 if (Type *Ty = D->getFriendType()) {
393 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
394 D->getLocation(), DeclarationName());
395 if (T.isNull()) return 0;
396
397 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
398 FU = T.getTypePtr();
399
400 // Handle everything else by appropriate substitution.
401 } else {
402 NamedDecl *ND = D->getFriendDecl();
403 assert(ND && "friend decl must be a decl or a type!");
404
Douglas Gregora735b202009-10-13 14:39:41 +0000405 // FIXME: We have a problem here, because the nested call to Visit(ND)
406 // will inject the thing that the friend references into the current
407 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000408 Decl *NewND;
409
410 // Hack to make this work almost well pending a rewrite.
411 if (ND->getDeclContext()->isRecord())
412 NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs);
Douglas Gregor7557a132009-12-24 20:56:24 +0000413 else if (D->wasSpecialization()) {
414 // Totally egregious hack to work around PR5866
415 return 0;
416 } else
John McCalle129d442009-12-17 23:21:11 +0000417 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000418 if (!NewND) return 0;
419
420 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
John McCall02cace72009-08-28 07:59:38 +0000423 FriendDecl *FD =
424 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
425 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000426 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000427 Owner->addDecl(FD);
428 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000429}
430
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000431Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
432 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregorac7610d2009-06-22 20:57:11 +0000434 // The expression in a static assertion is not potentially evaluated.
435 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000437 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000438 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000439 if (InstantiatedAssertExpr.isInvalid())
440 return 0;
441
Douglas Gregor43d9d922009-08-08 01:41:12 +0000442 OwningExprResult Message(SemaRef, D->getMessage());
443 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000444 Decl *StaticAssert
445 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000446 move(InstantiatedAssertExpr),
447 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000448 return StaticAssert;
449}
450
451Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000454 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000456 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000457 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000458 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459 Enum->startDefinition();
460
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000461 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000462
463 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
465 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000466 EC != ECEnd; ++EC) {
467 // The specified value for the enumerator.
468 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000469 if (Expr *UninstValue = EC->getInitExpr()) {
470 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000471 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000472 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
John McCallce3ff2b2009-08-25 22:02:44 +0000474 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000475 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000476
477 // Drop the initial value and continue.
478 bool isInvalid = false;
479 if (Value.isInvalid()) {
480 Value = SemaRef.Owned((Expr *)0);
481 isInvalid = true;
482 }
483
Mike Stump1eb44332009-09-09 15:08:12 +0000484 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
486 EC->getLocation(), EC->getIdentifier(),
487 move(Value));
488
489 if (isInvalid) {
490 if (EnumConst)
491 EnumConst->setInvalidDecl();
492 Enum->setInvalidDecl();
493 }
494
495 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000497 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000498 LastEnumConst = EnumConst;
499 }
500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000502 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000503 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000504 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
505 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000506 &Enumerators[0], Enumerators.size(),
507 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000508
509 return Enum;
510}
511
Douglas Gregor6477b692009-03-25 15:04:13 +0000512Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
513 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
514 return 0;
515}
516
Douglas Gregored9c0f92009-10-29 00:04:11 +0000517namespace {
518 class SortDeclByLocation {
519 SourceManager &SourceMgr;
520
521 public:
522 explicit SortDeclByLocation(SourceManager &SourceMgr)
523 : SourceMgr(SourceMgr) { }
524
525 bool operator()(const Decl *X, const Decl *Y) const {
526 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
527 Y->getLocation());
528 }
529 };
530}
531
John McCalle29ba202009-08-20 01:44:21 +0000532Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000533 // Create a local instantiation scope for this class template, which
534 // will contain the instantiations of the template parameters.
535 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000536 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000537 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000539 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000540
541 CXXRecordDecl *Pattern = D->getTemplatedDecl();
542 CXXRecordDecl *RecordInst
543 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
544 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000545 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
546 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000547
548 ClassTemplateDecl *Inst
549 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
550 D->getIdentifier(), InstParams, RecordInst, 0);
551 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000552 if (D->getFriendObjectKind())
553 Inst->setObjectOfFriendDecl(true);
554 else
555 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000556 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000557
558 // Trigger creation of the type for the instantiation.
559 SemaRef.Context.getTypeDeclType(RecordInst);
560
Douglas Gregor259571e2009-10-30 22:42:42 +0000561 // Finish handling of friends.
562 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000563 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000564 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000565
John McCall46460a62010-01-20 21:53:11 +0000566 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000567 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000568
569 // First, we sort the partial specializations by location, so
570 // that we instantiate them in the order they were declared.
571 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
572 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
573 P = D->getPartialSpecializations().begin(),
574 PEnd = D->getPartialSpecializations().end();
575 P != PEnd; ++P)
576 PartialSpecs.push_back(&*P);
577 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
578 SortDeclByLocation(SemaRef.SourceMgr));
579
580 // Instantiate all of the partial specializations of this member class
581 // template.
582 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
583 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
584
John McCalle29ba202009-08-20 01:44:21 +0000585 return Inst;
586}
587
Douglas Gregord60e1052009-08-27 16:57:43 +0000588Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000589TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
590 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000591 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
592
593 // Lookup the already-instantiated declaration in the instantiation
594 // of the class template and return that.
595 DeclContext::lookup_result Found
596 = Owner->lookup(ClassTemplate->getDeclName());
597 if (Found.first == Found.second)
598 return 0;
599
600 ClassTemplateDecl *InstClassTemplate
601 = dyn_cast<ClassTemplateDecl>(*Found.first);
602 if (!InstClassTemplate)
603 return 0;
604
605 Decl *DCanon = D->getCanonicalDecl();
606 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
607 P = InstClassTemplate->getPartialSpecializations().begin(),
608 PEnd = InstClassTemplate->getPartialSpecializations().end();
609 P != PEnd; ++P) {
610 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
611 return &*P;
612 }
613
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000614 return 0;
615}
616
617Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000618TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000619 // Create a local instantiation scope for this function template, which
620 // will contain the instantiations of the template parameters and then get
621 // merged with the local instantiation scope for the function template
622 // itself.
623 Sema::LocalInstantiationScope Scope(SemaRef);
624
Douglas Gregord60e1052009-08-27 16:57:43 +0000625 TemplateParameterList *TempParams = D->getTemplateParameters();
626 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000627 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000628 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000629
Douglas Gregora735b202009-10-13 14:39:41 +0000630 FunctionDecl *Instantiated = 0;
631 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
632 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
633 InstParams));
634 else
635 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
636 D->getTemplatedDecl(),
637 InstParams));
638
639 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000640 return 0;
641
John McCall46460a62010-01-20 21:53:11 +0000642 Instantiated->setAccess(D->getAccess());
643
Mike Stump1eb44332009-09-09 15:08:12 +0000644 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000645 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000646 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000647 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000648 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000649 assert(InstTemplate &&
650 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000651
652 // Link the instantiation back to the pattern *unless* this is a
653 // non-definition friend declaration.
654 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
655 !(InstTemplate->getFriendObjectKind() &&
656 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000657 InstTemplate->setInstantiatedFromMemberTemplate(D);
658
659 // Add non-friends into the owner.
660 if (!InstTemplate->getFriendObjectKind())
661 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000662 return InstTemplate;
663}
664
Douglas Gregord475b8d2009-03-25 21:17:03 +0000665Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
666 CXXRecordDecl *PrevDecl = 0;
667 if (D->isInjectedClassName())
668 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000669 else if (D->getPreviousDeclaration()) {
670 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
671 TemplateArgs);
672 if (!Prev) return 0;
673 PrevDecl = cast<CXXRecordDecl>(Prev);
674 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000675
676 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000677 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000678 D->getLocation(), D->getIdentifier(),
679 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000680 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000681 // FIXME: Check against AS_none is an ugly hack to work around the issue that
682 // the tag decls introduced by friend class declarations don't have an access
683 // specifier. Remove once this area of the code gets sorted out.
684 if (D->getAccess() != AS_none)
685 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000686 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000687 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000688
John McCall02cace72009-08-28 07:59:38 +0000689 // If the original function was part of a friend declaration,
690 // inherit its namespace state.
691 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
692 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
693
Anders Carlssond8b285f2009-09-01 04:26:58 +0000694 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
695
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000697 return Record;
698}
699
John McCall02cace72009-08-28 07:59:38 +0000700/// Normal class members are of more specific types and therefore
701/// don't make it here. This function serves two purposes:
702/// 1) instantiating function templates
703/// 2) substituting friend declarations
704/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000705Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000706 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000707 // Check whether there is already a function template specialization for
708 // this declaration.
709 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
710 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000711 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000712 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000713 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000714 TemplateArgs.getInnermost().getFlatArgumentList(),
715 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000716 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
718 FunctionTemplateSpecializationInfo *Info
719 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000720 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Douglas Gregor127102b2009-06-29 20:59:39 +0000722 // If we already have a function template specialization, return it.
723 if (Info)
724 return Info->Function;
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Douglas Gregor79c22782010-01-16 20:21:20 +0000727 bool MergeWithParentScope = (TemplateParams != 0) ||
728 !(isa<Decl>(Owner) &&
729 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
730 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Douglas Gregore53060f2009-06-25 22:08:12 +0000732 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000733 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000734 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000735 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000736
Douglas Gregore53060f2009-06-25 22:08:12 +0000737 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000738 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
739 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000740 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000741 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000742 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000743 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000744 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000745 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Douglas Gregore53060f2009-06-25 22:08:12 +0000747 // Attach the parameters
748 for (unsigned P = 0; P < Params.size(); ++P)
749 Params[P]->setOwningFunction(Function);
750 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000751
Douglas Gregora735b202009-10-13 14:39:41 +0000752 if (TemplateParams) {
753 // Our resulting instantiation is actually a function template, since we
754 // are substituting only the outer template parameters. For example, given
755 //
756 // template<typename T>
757 // struct X {
758 // template<typename U> friend void f(T, U);
759 // };
760 //
761 // X<int> x;
762 //
763 // We are instantiating the friend function template "f" within X<int>,
764 // which means substituting int for T, but leaving "f" as a friend function
765 // template.
766 // Build the function template itself.
767 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
768 Function->getLocation(),
769 Function->getDeclName(),
770 TemplateParams, Function);
771 Function->setDescribedFunctionTemplate(FunctionTemplate);
772 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000773 } else if (FunctionTemplate) {
774 // Record this function template specialization.
775 Function->setFunctionTemplateSpecialization(SemaRef.Context,
776 FunctionTemplate,
777 &TemplateArgs.getInnermost(),
778 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000779 }
Douglas Gregora735b202009-10-13 14:39:41 +0000780
Douglas Gregore53060f2009-06-25 22:08:12 +0000781 if (InitFunctionInstantiation(Function, D))
782 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregore53060f2009-06-25 22:08:12 +0000784 bool Redeclaration = false;
785 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000786
John McCall68263142009-11-18 22:49:29 +0000787 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
788 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
789
Douglas Gregora735b202009-10-13 14:39:41 +0000790 if (TemplateParams || !FunctionTemplate) {
791 // Look only into the namespace where the friend would be declared to
792 // find a previous declaration. This is the innermost enclosing namespace,
793 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000794 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000795
Douglas Gregora735b202009-10-13 14:39:41 +0000796 // In C++, the previous declaration we find might be a tag type
797 // (class or enum). In this case, the new declaration will hide the
798 // tag type. Note that this does does not apply if we're declaring a
799 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000800 if (Previous.isSingleTagDecl())
801 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000802 }
803
John McCall9f54ad42009-12-10 09:41:52 +0000804 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
805 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000806 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000807
Douglas Gregora735b202009-10-13 14:39:41 +0000808 // If the original function was part of a friend declaration,
809 // inherit its namespace state and add it to the owner.
810 NamedDecl *FromFriendD
811 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
812 if (FromFriendD->getFriendObjectKind()) {
813 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000814 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000815 if (TemplateParams) {
816 ToFriendD = cast<NamedDecl>(FunctionTemplate);
817 PrevDecl = FunctionTemplate->getPreviousDeclaration();
818 } else {
819 ToFriendD = Function;
820 PrevDecl = Function->getPreviousDeclaration();
821 }
822 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
823 if (!Owner->isDependentContext() && !PrevDecl)
824 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
825
826 if (!TemplateParams)
827 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
828 }
829
Douglas Gregore53060f2009-06-25 22:08:12 +0000830 return Function;
831}
832
Douglas Gregord60e1052009-08-27 16:57:43 +0000833Decl *
834TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
835 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000836 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
837 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000838 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000839 // We are creating a function template specialization from a function
840 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000841 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000842 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000843 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000844 TemplateArgs.getInnermost().getFlatArgumentList(),
845 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000846 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
848 FunctionTemplateSpecializationInfo *Info
849 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000850 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor6b906862009-08-21 00:16:32 +0000852 // If we already have a function template specialization, return it.
853 if (Info)
854 return Info->Function;
855 }
856
Douglas Gregor79c22782010-01-16 20:21:20 +0000857 bool MergeWithParentScope = (TemplateParams != 0) ||
858 !(isa<Decl>(Owner) &&
859 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
860 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000861
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000862 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000863 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000864 if (T.isNull())
865 return 0;
866
867 // Build the instantiated method declaration.
868 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000869 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregordec06662009-08-21 18:42:58 +0000871 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000872 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000873 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
874 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
875 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000876 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
877 Constructor->getLocation(),
878 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000879 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000880 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000881 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000882 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
883 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
884 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
885 SemaRef.Context.getCanonicalType(ClassTy));
886 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
887 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000888 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000889 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000890 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000891 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000892 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000893 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
894 ConvTy);
895 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
896 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000897 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000898 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000899 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000900 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000901 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000902 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000903 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000904 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000905
Douglas Gregord60e1052009-08-27 16:57:43 +0000906 if (TemplateParams) {
907 // Our resulting instantiation is actually a function template, since we
908 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000909 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000910 // template<typename T>
911 // struct X {
912 // template<typename U> void f(T, U);
913 // };
914 //
915 // X<int> x;
916 //
917 // We are instantiating the member template "f" within X<int>, which means
918 // substituting int for T, but leaving "f" as a member function template.
919 // Build the function template itself.
920 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
921 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000922 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000923 TemplateParams, Method);
924 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000925 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000926 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000927 } else if (FunctionTemplate) {
928 // Record this function template specialization.
929 Method->setFunctionTemplateSpecialization(SemaRef.Context,
930 FunctionTemplate,
931 &TemplateArgs.getInnermost(),
932 InsertPos);
933 } else {
934 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000935 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000936 }
937
Mike Stump1eb44332009-09-09 15:08:12 +0000938 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000939 // out-of-line, the instantiation will have the same lexical
940 // context (which will be a namespace scope) as the template.
941 if (D->isOutOfLine())
942 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor5545e162009-03-24 00:38:23 +0000944 // Attach the parameters
945 for (unsigned P = 0; P < Params.size(); ++P)
946 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000947 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000948
949 if (InitMethodInstantiation(Method, D))
950 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000951
John McCall68263142009-11-18 22:49:29 +0000952 LookupResult Previous(SemaRef, Name, SourceLocation(),
953 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregord60e1052009-08-27 16:57:43 +0000955 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000956 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregordec06662009-08-21 18:42:58 +0000958 // In C++, the previous declaration we find might be a tag type
959 // (class or enum). In this case, the new declaration will hide the
960 // tag type. Note that this does does not apply if we're declaring a
961 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000962 if (Previous.isSingleTagDecl())
963 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000964 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000965
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000966 bool Redeclaration = false;
967 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000968 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000969 /*FIXME:*/OverloadableAttrRequired);
970
Douglas Gregor4ba31362009-12-01 17:24:26 +0000971 if (D->isPure())
972 SemaRef.CheckPureMethod(Method, SourceRange());
973
John McCall46460a62010-01-20 21:53:11 +0000974 Method->setAccess(D->getAccess());
975
John McCall68263142009-11-18 22:49:29 +0000976 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000977 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000978 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000980 return Method;
981}
982
Douglas Gregor615c5d42009-03-24 16:43:20 +0000983Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000984 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000985}
986
Douglas Gregor03b2b072009-03-24 00:15:49 +0000987Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000988 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000989}
990
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000991Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000992 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000993}
994
Douglas Gregor6477b692009-03-25 15:04:13 +0000995ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000996 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000997 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000998 if (DI) {
999 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1000 D->getDeclName());
1001 if (DI) T = DI->getType();
1002 } else {
1003 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1004 D->getDeclName());
1005 DI = 0;
1006 }
1007
1008 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001009 return 0;
1010
John McCall58e46772009-10-23 21:48:59 +00001011 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001012
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001013 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001014 ParmVarDecl *Param
1015 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1016 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001017
Anders Carlsson9351c172009-08-25 03:18:48 +00001018 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001019 if (D->hasUninstantiatedDefaultArg())
1020 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001021 else if (Expr *Arg = D->getDefaultArg())
1022 Param->setUninstantiatedDefaultArg(Arg);
1023
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001024 // Note: we don't try to instantiate function parameters until after
1025 // we've instantiated the function's type. Therefore, we don't have
1026 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001027 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001028 return Param;
1029}
1030
John McCalle29ba202009-08-20 01:44:21 +00001031Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1032 TemplateTypeParmDecl *D) {
1033 // TODO: don't always clone when decls are refcounted.
1034 const Type* T = D->getTypeForDecl();
1035 assert(T->isTemplateTypeParmType());
1036 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCalle29ba202009-08-20 01:44:21 +00001038 TemplateTypeParmDecl *Inst =
1039 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001040 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001041 TTPT->getName(),
1042 D->wasDeclaredWithTypename(),
1043 D->isParameterPack());
1044
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001045 if (D->hasDefaultArgument())
1046 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001047
Douglas Gregor550d9b22009-10-31 17:21:17 +00001048 // Introduce this template parameter's instantiation into the instantiation
1049 // scope.
1050 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1051
John McCalle29ba202009-08-20 01:44:21 +00001052 return Inst;
1053}
1054
Douglas Gregor33642df2009-10-23 23:25:44 +00001055Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1056 NonTypeTemplateParmDecl *D) {
1057 // Substitute into the type of the non-type template parameter.
1058 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001059 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001060 if (DI) {
1061 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1062 D->getDeclName());
1063 if (DI) T = DI->getType();
1064 } else {
1065 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1066 D->getDeclName());
1067 DI = 0;
1068 }
1069 if (T.isNull())
1070 return 0;
1071
1072 // Check that this type is acceptable for a non-type template parameter.
1073 bool Invalid = false;
1074 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1075 if (T.isNull()) {
1076 T = SemaRef.Context.IntTy;
1077 Invalid = true;
1078 }
1079
1080 NonTypeTemplateParmDecl *Param
1081 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1082 D->getDepth() - 1, D->getPosition(),
1083 D->getIdentifier(), T, DI);
1084 if (Invalid)
1085 Param->setInvalidDecl();
1086
1087 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001088
1089 // Introduce this template parameter's instantiation into the instantiation
1090 // scope.
1091 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001092 return Param;
1093}
1094
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001095Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001096TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1097 TemplateTemplateParmDecl *D) {
1098 // Instantiate the template parameter list of the template template parameter.
1099 TemplateParameterList *TempParams = D->getTemplateParameters();
1100 TemplateParameterList *InstParams;
1101 {
1102 // Perform the actual substitution of template parameters within a new,
1103 // local instantiation scope.
1104 Sema::LocalInstantiationScope Scope(SemaRef);
1105 InstParams = SubstTemplateParams(TempParams);
1106 if (!InstParams)
1107 return NULL;
1108 }
1109
1110 // Build the template template parameter.
1111 TemplateTemplateParmDecl *Param
1112 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1113 D->getDepth() - 1, D->getPosition(),
1114 D->getIdentifier(), InstParams);
1115 Param->setDefaultArgument(D->getDefaultArgument());
1116
1117 // Introduce this template parameter's instantiation into the instantiation
1118 // scope.
1119 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1120
1121 return Param;
1122}
1123
Douglas Gregor48c32a72009-11-17 06:07:40 +00001124Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1125 // Using directives are never dependent, so they require no explicit
1126
1127 UsingDirectiveDecl *Inst
1128 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1129 D->getNamespaceKeyLocation(),
1130 D->getQualifierRange(), D->getQualifier(),
1131 D->getIdentLocation(),
1132 D->getNominatedNamespace(),
1133 D->getCommonAncestor());
1134 Owner->addDecl(Inst);
1135 return Inst;
1136}
1137
John McCalled976492009-12-04 22:46:56 +00001138Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1139 // The nested name specifier is non-dependent, so no transformation
1140 // is required.
1141
John McCall9f54ad42009-12-10 09:41:52 +00001142 // We only need to do redeclaration lookups if we're in a class
1143 // scope (in fact, it's not really even possible in non-class
1144 // scopes).
1145 bool CheckRedeclaration = Owner->isRecord();
1146
1147 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1148 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1149
John McCalled976492009-12-04 22:46:56 +00001150 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1151 D->getLocation(),
1152 D->getNestedNameRange(),
1153 D->getUsingLocation(),
1154 D->getTargetNestedNameDecl(),
1155 D->getDeclName(),
1156 D->isTypeName());
1157
1158 CXXScopeSpec SS;
1159 SS.setScopeRep(D->getTargetNestedNameDecl());
1160 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001161
1162 if (CheckRedeclaration) {
1163 Prev.setHideTags(false);
1164 SemaRef.LookupQualifiedName(Prev, Owner);
1165
1166 // Check for invalid redeclarations.
1167 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1168 D->isTypeName(), SS,
1169 D->getLocation(), Prev))
1170 NewUD->setInvalidDecl();
1171
1172 }
1173
1174 if (!NewUD->isInvalidDecl() &&
1175 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001176 D->getLocation()))
1177 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001178
John McCalled976492009-12-04 22:46:56 +00001179 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1180 NewUD->setAccess(D->getAccess());
1181 Owner->addDecl(NewUD);
1182
John McCall9f54ad42009-12-10 09:41:52 +00001183 // Don't process the shadow decls for an invalid decl.
1184 if (NewUD->isInvalidDecl())
1185 return NewUD;
1186
John McCall323c3102009-12-22 22:26:37 +00001187 bool isFunctionScope = Owner->isFunctionOrMethod();
1188
John McCall9f54ad42009-12-10 09:41:52 +00001189 // Process the shadow decls.
1190 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1191 I != E; ++I) {
1192 UsingShadowDecl *Shadow = *I;
1193 NamedDecl *InstTarget =
1194 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1195 TemplateArgs));
1196
1197 if (CheckRedeclaration &&
1198 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1199 continue;
1200
1201 UsingShadowDecl *InstShadow
1202 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1203 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001204
1205 if (isFunctionScope)
1206 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001207 }
John McCalled976492009-12-04 22:46:56 +00001208
1209 return NewUD;
1210}
1211
1212Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001213 // Ignore these; we handle them in bulk when processing the UsingDecl.
1214 return 0;
John McCalled976492009-12-04 22:46:56 +00001215}
1216
John McCall7ba107a2009-11-18 02:36:19 +00001217Decl * TemplateDeclInstantiator
1218 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 NestedNameSpecifier *NNS =
1220 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1221 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001222 TemplateArgs);
1223 if (!NNS)
1224 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001226 CXXScopeSpec SS;
1227 SS.setRange(D->getTargetNestedNameRange());
1228 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
1230 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001231 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001232 D->getUsingLoc(), SS, D->getLocation(),
1233 D->getDeclName(), 0,
1234 /*instantiation*/ true,
1235 /*typename*/ true, D->getTypenameLoc());
1236 if (UD)
John McCalled976492009-12-04 22:46:56 +00001237 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1238
John McCall7ba107a2009-11-18 02:36:19 +00001239 return UD;
1240}
1241
1242Decl * TemplateDeclInstantiator
1243 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1244 NestedNameSpecifier *NNS =
1245 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1246 D->getTargetNestedNameRange(),
1247 TemplateArgs);
1248 if (!NNS)
1249 return 0;
1250
1251 CXXScopeSpec SS;
1252 SS.setRange(D->getTargetNestedNameRange());
1253 SS.setScopeRep(NNS);
1254
1255 NamedDecl *UD =
1256 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1257 D->getUsingLoc(), SS, D->getLocation(),
1258 D->getDeclName(), 0,
1259 /*instantiation*/ true,
1260 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001261 if (UD)
John McCalled976492009-12-04 22:46:56 +00001262 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1263
Anders Carlsson0d8df782009-08-29 19:37:28 +00001264 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001265}
1266
John McCallce3ff2b2009-08-25 22:02:44 +00001267Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001268 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001269 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001270 return Instantiator.Visit(D);
1271}
1272
John McCalle29ba202009-08-20 01:44:21 +00001273/// \brief Instantiates a nested template parameter list in the current
1274/// instantiation context.
1275///
1276/// \param L The parameter list to instantiate
1277///
1278/// \returns NULL if there was an error
1279TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001280TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001281 // Get errors for all the parameters before bailing out.
1282 bool Invalid = false;
1283
1284 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001285 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001286 ParamVector Params;
1287 Params.reserve(N);
1288 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1289 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001290 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001291 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001292 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001293 }
1294
1295 // Clean up if we had an error.
1296 if (Invalid) {
1297 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1298 PI != PE; ++PI)
1299 if (*PI)
1300 (*PI)->Destroy(SemaRef.Context);
1301 return NULL;
1302 }
1303
1304 TemplateParameterList *InstL
1305 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1306 L->getLAngleLoc(), &Params.front(), N,
1307 L->getRAngleLoc());
1308 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001309}
John McCalle29ba202009-08-20 01:44:21 +00001310
Douglas Gregored9c0f92009-10-29 00:04:11 +00001311/// \brief Instantiate the declaration of a class template partial
1312/// specialization.
1313///
1314/// \param ClassTemplate the (instantiated) class template that is partially
1315// specialized by the instantiation of \p PartialSpec.
1316///
1317/// \param PartialSpec the (uninstantiated) class template partial
1318/// specialization that we are instantiating.
1319///
1320/// \returns true if there was an error, false otherwise.
1321bool
1322TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1323 ClassTemplateDecl *ClassTemplate,
1324 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001325 // Create a local instantiation scope for this class template partial
1326 // specialization, which will contain the instantiations of the template
1327 // parameters.
1328 Sema::LocalInstantiationScope Scope(SemaRef);
1329
Douglas Gregored9c0f92009-10-29 00:04:11 +00001330 // Substitute into the template parameters of the class template partial
1331 // specialization.
1332 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1333 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1334 if (!InstParams)
1335 return true;
1336
1337 // Substitute into the template arguments of the class template partial
1338 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001339 const TemplateArgumentLoc *PartialSpecTemplateArgs
1340 = PartialSpec->getTemplateArgsAsWritten();
1341 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1342
John McCalld5532b62009-11-23 01:53:49 +00001343 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001344 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001345 TemplateArgumentLoc Loc;
1346 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001347 return true;
John McCalld5532b62009-11-23 01:53:49 +00001348 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001349 }
1350
1351
1352 // Check that the template argument list is well-formed for this
1353 // class template.
1354 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1355 InstTemplateArgs.size());
1356 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1357 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001358 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001359 false,
1360 Converted))
1361 return true;
1362
1363 // Figure out where to insert this class template partial specialization
1364 // in the member template's set of class template partial specializations.
1365 llvm::FoldingSetNodeID ID;
1366 ClassTemplatePartialSpecializationDecl::Profile(ID,
1367 Converted.getFlatArguments(),
1368 Converted.flatSize(),
1369 SemaRef.Context);
1370 void *InsertPos = 0;
1371 ClassTemplateSpecializationDecl *PrevDecl
1372 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1373 InsertPos);
1374
1375 // Build the canonical type that describes the converted template
1376 // arguments of the class template partial specialization.
1377 QualType CanonType
1378 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1379 Converted.getFlatArguments(),
1380 Converted.flatSize());
1381
1382 // Build the fully-sugared type for this class template
1383 // specialization as the user wrote in the specialization
1384 // itself. This means that we'll pretty-print the type retrieved
1385 // from the specialization's declaration the way that the user
1386 // actually wrote the specialization, rather than formatting the
1387 // name based on the "canonical" representation used to store the
1388 // template arguments in the specialization.
1389 QualType WrittenTy
1390 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001391 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001392 CanonType);
1393
1394 if (PrevDecl) {
1395 // We've already seen a partial specialization with the same template
1396 // parameters and template arguments. This can happen, for example, when
1397 // substituting the outer template arguments ends up causing two
1398 // class template partial specializations of a member class template
1399 // to have identical forms, e.g.,
1400 //
1401 // template<typename T, typename U>
1402 // struct Outer {
1403 // template<typename X, typename Y> struct Inner;
1404 // template<typename Y> struct Inner<T, Y>;
1405 // template<typename Y> struct Inner<U, Y>;
1406 // };
1407 //
1408 // Outer<int, int> outer; // error: the partial specializations of Inner
1409 // // have the same signature.
1410 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1411 << WrittenTy;
1412 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1413 << SemaRef.Context.getTypeDeclType(PrevDecl);
1414 return true;
1415 }
1416
1417
1418 // Create the class template partial specialization declaration.
1419 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1420 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1421 PartialSpec->getLocation(),
1422 InstParams,
1423 ClassTemplate,
1424 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001425 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001426 0);
1427 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1428 InstPartialSpec->setTypeAsWritten(WrittenTy);
1429
1430 // Add this partial specialization to the set of class template partial
1431 // specializations.
1432 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1433 InsertPos);
1434 return false;
1435}
1436
John McCallce3ff2b2009-08-25 22:02:44 +00001437/// \brief Does substitution on the type of the given function, including
1438/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001439///
John McCallce3ff2b2009-08-25 22:02:44 +00001440/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001441///
1442/// \param Params the instantiated parameter declarations
1443
John McCallce3ff2b2009-08-25 22:02:44 +00001444/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001445/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001446QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001447TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001448 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1449 bool InvalidDecl = false;
1450
John McCallce3ff2b2009-08-25 22:02:44 +00001451 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001452 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001453 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001454 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001455 PEnd = D->param_end();
1456 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001457 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001458 if (PInst->getType()->isVoidType()) {
1459 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1460 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001461 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001462 PInst->getType(),
1463 diag::err_abstract_type_in_decl,
1464 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001465 PInst->setInvalidDecl();
1466
1467 Params.push_back(PInst);
1468 ParamTys.push_back(PInst->getType());
1469
1470 if (PInst->isInvalidDecl())
1471 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001472 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001473 InvalidDecl = true;
1474 }
1475
1476 // FIXME: Deallocate dead declarations.
1477 if (InvalidDecl)
1478 return QualType();
1479
John McCall183700f2009-09-21 23:43:11 +00001480 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001481 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001482 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001483 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1484 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001485 if (ResultType.isNull())
1486 return QualType();
1487
Jay Foadbeaaccd2009-05-21 09:52:38 +00001488 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001489 Proto->isVariadic(), Proto->getTypeQuals(),
1490 D->getLocation(), D->getDeclName());
1491}
1492
Mike Stump1eb44332009-09-09 15:08:12 +00001493/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001494/// declaration (New) from the corresponding fields of its template (Tmpl).
1495///
1496/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001497bool
1498TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001499 FunctionDecl *Tmpl) {
1500 if (Tmpl->isDeleted())
1501 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Douglas Gregorcca9e962009-07-01 22:01:06 +00001503 // If we are performing substituting explicitly-specified template arguments
1504 // or deduced template arguments into a function template and we reach this
1505 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001506 // to keeping the new function template specialization. We therefore
1507 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001508 // into a template instantiation for this specific function template
1509 // specialization, which is not a SFINAE context, so that we diagnose any
1510 // further errors in the declaration itself.
1511 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1512 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1513 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1514 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001515 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001516 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001517 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001518 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001519 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001520 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1521 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001522 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001523 }
1524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001526 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1527 assert(Proto && "Function template without prototype?");
1528
1529 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1530 Proto->getNoReturnAttr()) {
1531 // The function has an exception specification or a "noreturn"
1532 // attribute. Substitute into each of the exception types.
1533 llvm::SmallVector<QualType, 4> Exceptions;
1534 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1535 // FIXME: Poor location information!
1536 QualType T
1537 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1538 New->getLocation(), New->getDeclName());
1539 if (T.isNull() ||
1540 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1541 continue;
1542
1543 Exceptions.push_back(T);
1544 }
1545
1546 // Rebuild the function type
1547
1548 const FunctionProtoType *NewProto
1549 = New->getType()->getAs<FunctionProtoType>();
1550 assert(NewProto && "Template instantiation without function prototype?");
1551 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1552 NewProto->arg_type_begin(),
1553 NewProto->getNumArgs(),
1554 NewProto->isVariadic(),
1555 NewProto->getTypeQuals(),
1556 Proto->hasExceptionSpec(),
1557 Proto->hasAnyExceptionSpec(),
1558 Exceptions.size(),
1559 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001560 Proto->getNoReturnAttr(),
1561 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001562 }
1563
Douglas Gregore53060f2009-06-25 22:08:12 +00001564 return false;
1565}
1566
Douglas Gregor5545e162009-03-24 00:38:23 +00001567/// \brief Initializes common fields of an instantiated method
1568/// declaration (New) from the corresponding fields of its template
1569/// (Tmpl).
1570///
1571/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001572bool
1573TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001574 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001575 if (InitFunctionInstantiation(New, Tmpl))
1576 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregor5545e162009-03-24 00:38:23 +00001578 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1579 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001580 if (Tmpl->isVirtualAsWritten())
1581 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001582
1583 // FIXME: attributes
1584 // FIXME: New needs a pointer to Tmpl
1585 return false;
1586}
Douglas Gregora58861f2009-05-13 20:28:22 +00001587
1588/// \brief Instantiate the definition of the given function from its
1589/// template.
1590///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001591/// \param PointOfInstantiation the point at which the instantiation was
1592/// required. Note that this is not precisely a "point of instantiation"
1593/// for the function, but it's close.
1594///
Douglas Gregora58861f2009-05-13 20:28:22 +00001595/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001596/// function template specialization or member function of a class template
1597/// specialization.
1598///
1599/// \param Recursive if true, recursively instantiates any functions that
1600/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001601///
1602/// \param DefinitionRequired if true, then we are performing an explicit
1603/// instantiation where the body of the function is required. Complain if
1604/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001605void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001606 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001607 bool Recursive,
1608 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001609 if (Function->isInvalidDecl())
1610 return;
1611
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001612 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001614 // Never instantiate an explicit specialization.
1615 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1616 return;
1617
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001618 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001619 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001620 Stmt *Pattern = 0;
1621 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001622 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001623
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001624 if (!Pattern) {
1625 if (DefinitionRequired) {
1626 if (Function->getPrimaryTemplate())
1627 Diag(PointOfInstantiation,
1628 diag::err_explicit_instantiation_undefined_func_template)
1629 << Function->getPrimaryTemplate();
1630 else
1631 Diag(PointOfInstantiation,
1632 diag::err_explicit_instantiation_undefined_member)
1633 << 1 << Function->getDeclName() << Function->getDeclContext();
1634
1635 if (PatternDecl)
1636 Diag(PatternDecl->getLocation(),
1637 diag::note_explicit_instantiation_here);
1638 }
1639
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001640 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001641 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001642
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001643 // C++0x [temp.explicit]p9:
1644 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001645 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001646 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001647 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001648 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001649 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001650 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001652 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1653 if (Inst)
1654 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001655
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001656 // If we're performing recursive template instantiation, create our own
1657 // queue of pending implicit instantiations that we will instantiate later,
1658 // while we're still within our own instantiation context.
1659 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1660 if (Recursive)
1661 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001663 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1664
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001665 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001666 // recorded, unless we're actually a member function within a local
1667 // class, in which case we need to merge our results with the parent
1668 // scope (of the enclosing function).
1669 bool MergeWithParentScope = false;
1670 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1671 MergeWithParentScope = Rec->isLocalClass();
1672
1673 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001675 // Introduce the instantiated function parameters into the local
1676 // instantiation scope.
1677 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1678 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1679 Function->getParamDecl(I));
1680
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001681 // Enter the scope of this instantiation. We don't use
1682 // PushDeclContext because we don't have a scope.
1683 DeclContext *PreviousContext = CurContext;
1684 CurContext = Function;
1685
Mike Stump1eb44332009-09-09 15:08:12 +00001686 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001687 getTemplateInstantiationArgs(Function);
1688
1689 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001690 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001691 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1692 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1693 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001694 }
1695
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001696 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001697 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001698
Douglas Gregor52604ab2009-09-11 21:19:12 +00001699 if (Body.isInvalid())
1700 Function->setInvalidDecl();
1701
Mike Stump1eb44332009-09-09 15:08:12 +00001702 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001703 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001704
1705 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001706
1707 DeclGroupRef DG(Function);
1708 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Douglas Gregor60406be2010-01-16 22:29:39 +00001710 // This class may have local implicit instantiations that need to be
1711 // instantiation within this scope.
1712 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1713 Scope.Exit();
1714
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001715 if (Recursive) {
1716 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001717 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001718 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001720 // Restore the set of pending implicit instantiations.
1721 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1722 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001723}
1724
1725/// \brief Instantiate the definition of the given variable from its
1726/// template.
1727///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001728/// \param PointOfInstantiation the point at which the instantiation was
1729/// required. Note that this is not precisely a "point of instantiation"
1730/// for the function, but it's close.
1731///
1732/// \param Var the already-instantiated declaration of a static member
1733/// variable of a class template specialization.
1734///
1735/// \param Recursive if true, recursively instantiates any functions that
1736/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001737///
1738/// \param DefinitionRequired if true, then we are performing an explicit
1739/// instantiation where an out-of-line definition of the member variable
1740/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001741void Sema::InstantiateStaticDataMemberDefinition(
1742 SourceLocation PointOfInstantiation,
1743 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001744 bool Recursive,
1745 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001746 if (Var->isInvalidDecl())
1747 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Douglas Gregor7caa6822009-07-24 20:34:43 +00001749 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001750 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001751 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001752 assert(Def->isStaticDataMember() && "Not a static data member?");
1753 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregor0d035142009-10-27 18:42:08 +00001755 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001756 // We did not find an out-of-line definition of this static data member,
1757 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001758 // instantiate this definition (or provide a specialization for it) in
1759 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001760 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001761 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001762 Diag(PointOfInstantiation,
1763 diag::err_explicit_instantiation_undefined_member)
1764 << 2 << Var->getDeclName() << Var->getDeclContext();
1765 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1766 }
1767
Douglas Gregor7caa6822009-07-24 20:34:43 +00001768 return;
1769 }
1770
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001771 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001772 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001773 return;
1774
1775 // C++0x [temp.explicit]p9:
1776 // Except for inline functions, other explicit instantiation declarations
1777 // have the effect of suppressing the implicit instantiation of the entity
1778 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001779 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001780 == TSK_ExplicitInstantiationDeclaration)
1781 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor7caa6822009-07-24 20:34:43 +00001783 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1784 if (Inst)
1785 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor7caa6822009-07-24 20:34:43 +00001787 // If we're performing recursive template instantiation, create our own
1788 // queue of pending implicit instantiations that we will instantiate later,
1789 // while we're still within our own instantiation context.
1790 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1791 if (Recursive)
1792 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Douglas Gregor7caa6822009-07-24 20:34:43 +00001794 // Enter the scope of this instantiation. We don't use
1795 // PushDeclContext because we don't have a scope.
1796 DeclContext *PreviousContext = CurContext;
1797 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001799 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001800 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001801 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001802 CurContext = PreviousContext;
1803
1804 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001805 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001806 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1807 assert(MSInfo && "Missing member specialization information?");
1808 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1809 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001810 DeclGroupRef DG(Var);
1811 Consumer.HandleTopLevelDecl(DG);
1812 }
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor7caa6822009-07-24 20:34:43 +00001814 if (Recursive) {
1815 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001816 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001817 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregor7caa6822009-07-24 20:34:43 +00001819 // Restore the set of pending implicit instantiations.
1820 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001821 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001822}
Douglas Gregor815215d2009-05-27 05:35:12 +00001823
Anders Carlsson09025312009-08-29 05:16:22 +00001824void
1825Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1826 const CXXConstructorDecl *Tmpl,
1827 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson09025312009-08-29 05:16:22 +00001829 llvm::SmallVector<MemInitTy*, 4> NewInits;
1830
1831 // Instantiate all the initializers.
1832 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001833 InitsEnd = Tmpl->init_end();
1834 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001835 CXXBaseOrMemberInitializer *Init = *Inits;
1836
1837 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Anders Carlsson09025312009-08-29 05:16:22 +00001839 // Instantiate all the arguments.
1840 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1841 Args != ArgsEnd; ++Args) {
1842 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1843
1844 if (NewArg.isInvalid())
1845 New->setInvalidDecl();
1846 else
1847 NewArgs.push_back(NewArg.takeAs<Expr>());
1848 }
1849
1850 MemInitResult NewInit;
1851
1852 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001853 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001854 TemplateArgs,
1855 Init->getSourceLocation(),
1856 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001857 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001858 New->setInvalidDecl();
1859 continue;
1860 }
1861
John McCalla93c9342009-12-07 02:54:59 +00001862 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001863 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001864 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001865 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001866 Init->getRParenLoc(),
1867 New->getParent());
1868 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001869 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001871 // Is this an anonymous union?
1872 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001873 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001874 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001875 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1876 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001877
1878 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001879 NewArgs.size(),
1880 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001881 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001882 Init->getRParenLoc());
1883 }
1884
1885 if (NewInit.isInvalid())
1886 New->setInvalidDecl();
1887 else {
1888 // FIXME: It would be nice if ASTOwningVector had a release function.
1889 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Anders Carlsson09025312009-08-29 05:16:22 +00001891 NewInits.push_back((MemInitTy *)NewInit.get());
1892 }
1893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anders Carlsson09025312009-08-29 05:16:22 +00001895 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001896 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001897 /*FIXME: ColonLoc */
1898 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001899 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001900}
1901
John McCall52a575a2009-08-29 08:11:13 +00001902// TODO: this could be templated if the various decl types used the
1903// same method name.
1904static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1905 ClassTemplateDecl *Instance) {
1906 Pattern = Pattern->getCanonicalDecl();
1907
1908 do {
1909 Instance = Instance->getCanonicalDecl();
1910 if (Pattern == Instance) return true;
1911 Instance = Instance->getInstantiatedFromMemberTemplate();
1912 } while (Instance);
1913
1914 return false;
1915}
1916
Douglas Gregor0d696532009-09-28 06:34:35 +00001917static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1918 FunctionTemplateDecl *Instance) {
1919 Pattern = Pattern->getCanonicalDecl();
1920
1921 do {
1922 Instance = Instance->getCanonicalDecl();
1923 if (Pattern == Instance) return true;
1924 Instance = Instance->getInstantiatedFromMemberTemplate();
1925 } while (Instance);
1926
1927 return false;
1928}
1929
Douglas Gregored9c0f92009-10-29 00:04:11 +00001930static bool
1931isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1932 ClassTemplatePartialSpecializationDecl *Instance) {
1933 Pattern
1934 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1935 do {
1936 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1937 Instance->getCanonicalDecl());
1938 if (Pattern == Instance)
1939 return true;
1940 Instance = Instance->getInstantiatedFromMember();
1941 } while (Instance);
1942
1943 return false;
1944}
1945
John McCall52a575a2009-08-29 08:11:13 +00001946static bool isInstantiationOf(CXXRecordDecl *Pattern,
1947 CXXRecordDecl *Instance) {
1948 Pattern = Pattern->getCanonicalDecl();
1949
1950 do {
1951 Instance = Instance->getCanonicalDecl();
1952 if (Pattern == Instance) return true;
1953 Instance = Instance->getInstantiatedFromMemberClass();
1954 } while (Instance);
1955
1956 return false;
1957}
1958
1959static bool isInstantiationOf(FunctionDecl *Pattern,
1960 FunctionDecl *Instance) {
1961 Pattern = Pattern->getCanonicalDecl();
1962
1963 do {
1964 Instance = Instance->getCanonicalDecl();
1965 if (Pattern == Instance) return true;
1966 Instance = Instance->getInstantiatedFromMemberFunction();
1967 } while (Instance);
1968
1969 return false;
1970}
1971
1972static bool isInstantiationOf(EnumDecl *Pattern,
1973 EnumDecl *Instance) {
1974 Pattern = Pattern->getCanonicalDecl();
1975
1976 do {
1977 Instance = Instance->getCanonicalDecl();
1978 if (Pattern == Instance) return true;
1979 Instance = Instance->getInstantiatedFromMemberEnum();
1980 } while (Instance);
1981
1982 return false;
1983}
1984
John McCalled976492009-12-04 22:46:56 +00001985static bool isInstantiationOf(UsingShadowDecl *Pattern,
1986 UsingShadowDecl *Instance,
1987 ASTContext &C) {
1988 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1989}
1990
1991static bool isInstantiationOf(UsingDecl *Pattern,
1992 UsingDecl *Instance,
1993 ASTContext &C) {
1994 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1995}
1996
John McCall7ba107a2009-11-18 02:36:19 +00001997static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1998 UsingDecl *Instance,
1999 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002000 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002001}
2002
2003static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002004 UsingDecl *Instance,
2005 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002006 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002007}
2008
John McCall52a575a2009-08-29 08:11:13 +00002009static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2010 VarDecl *Instance) {
2011 assert(Instance->isStaticDataMember());
2012
2013 Pattern = Pattern->getCanonicalDecl();
2014
2015 do {
2016 Instance = Instance->getCanonicalDecl();
2017 if (Pattern == Instance) return true;
2018 Instance = Instance->getInstantiatedFromStaticDataMember();
2019 } while (Instance);
2020
2021 return false;
2022}
2023
John McCalled976492009-12-04 22:46:56 +00002024// Other is the prospective instantiation
2025// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002026static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002027 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002028 if (UnresolvedUsingTypenameDecl *UUD
2029 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2030 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2031 return isInstantiationOf(UUD, UD, Ctx);
2032 }
2033 }
2034
2035 if (UnresolvedUsingValueDecl *UUD
2036 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002037 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2038 return isInstantiationOf(UUD, UD, Ctx);
2039 }
2040 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002041
Anders Carlsson0d8df782009-08-29 19:37:28 +00002042 return false;
2043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
John McCall52a575a2009-08-29 08:11:13 +00002045 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2046 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
John McCall52a575a2009-08-29 08:11:13 +00002048 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2049 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002050
John McCall52a575a2009-08-29 08:11:13 +00002051 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2052 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002053
Douglas Gregor7caa6822009-07-24 20:34:43 +00002054 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002055 if (Var->isStaticDataMember())
2056 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2057
2058 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2059 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002060
Douglas Gregor0d696532009-09-28 06:34:35 +00002061 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2062 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2063
Douglas Gregored9c0f92009-10-29 00:04:11 +00002064 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2065 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2066 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2067 PartialSpec);
2068
Anders Carlssond8b285f2009-09-01 04:26:58 +00002069 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2070 if (!Field->getDeclName()) {
2071 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002072 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002073 cast<FieldDecl>(D);
2074 }
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
John McCalled976492009-12-04 22:46:56 +00002077 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2078 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2079
2080 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2081 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2082
Douglas Gregor815215d2009-05-27 05:35:12 +00002083 return D->getDeclName() && isa<NamedDecl>(Other) &&
2084 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2085}
2086
2087template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002088static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002089 NamedDecl *D,
2090 ForwardIterator first,
2091 ForwardIterator last) {
2092 for (; first != last; ++first)
2093 if (isInstantiationOf(Ctx, D, *first))
2094 return cast<NamedDecl>(*first);
2095
2096 return 0;
2097}
2098
John McCall02cace72009-08-28 07:59:38 +00002099/// \brief Finds the instantiation of the given declaration context
2100/// within the current instantiation.
2101///
2102/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002103DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2104 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002105 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002106 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002107 return cast_or_null<DeclContext>(ID);
2108 } else return DC;
2109}
2110
Douglas Gregored961e72009-05-27 17:54:46 +00002111/// \brief Find the instantiation of the given declaration within the
2112/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002113///
2114/// This routine is intended to be used when \p D is a declaration
2115/// referenced from within a template, that needs to mapped into the
2116/// corresponding declaration within an instantiation. For example,
2117/// given:
2118///
2119/// \code
2120/// template<typename T>
2121/// struct X {
2122/// enum Kind {
2123/// KnownValue = sizeof(T)
2124/// };
2125///
2126/// bool getKind() const { return KnownValue; }
2127/// };
2128///
2129/// template struct X<int>;
2130/// \endcode
2131///
2132/// In the instantiation of X<int>::getKind(), we need to map the
2133/// EnumConstantDecl for KnownValue (which refers to
2134/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002135/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2136/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002137NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2138 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002139 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002140 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2141 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2142 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002143 // D is a local of some kind. Look into the map of local
2144 // declarations to their instantiations.
2145 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2146 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002147
Douglas Gregore95b4092009-09-16 18:34:49 +00002148 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2149 if (!Record->isDependentContext())
2150 return D;
2151
2152 // If the RecordDecl is actually the injected-class-name or a "templated"
2153 // declaration for a class template or class template partial
2154 // specialization, substitute into the injected-class-name of the
2155 // class template or partial specialization to find the new DeclContext.
2156 QualType T;
2157 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2158
2159 if (ClassTemplate) {
2160 T = ClassTemplate->getInjectedClassNameType(Context);
2161 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2162 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2163 T = Context.getTypeDeclType(Record);
2164 ClassTemplate = PartialSpec->getSpecializedTemplate();
2165 }
2166
2167 if (!T.isNull()) {
2168 // Substitute into the injected-class-name to get the type corresponding
2169 // to the instantiation we want. This substitution should never fail,
2170 // since we know we can instantiate the injected-class-name or we wouldn't
2171 // have gotten to the injected-class-name!
2172 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2173 // instantiation in the common case?
2174 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2175 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2176
2177 if (!T->isDependentType()) {
2178 assert(T->isRecordType() && "Instantiation must produce a record type");
2179 return T->getAs<RecordType>()->getDecl();
2180 }
2181
2182 // We are performing "partial" template instantiation to create the
2183 // member declarations for the members of a class template
2184 // specialization. Therefore, D is actually referring to something in
2185 // the current instantiation. Look through the current context,
2186 // which contains actual instantiations, to find the instantiation of
2187 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002188 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002189 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002190 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002191 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002192 if (isInstantiationOf(ClassTemplate,
2193 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002194 return Spec;
2195 }
2196
Mike Stump1eb44332009-09-09 15:08:12 +00002197 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002198 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002199 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002200 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002201
2202 // Fall through to deal with other dependent record types (e.g.,
2203 // anonymous unions in class templates).
2204 }
John McCall52a575a2009-08-29 08:11:13 +00002205
Douglas Gregore95b4092009-09-16 18:34:49 +00002206 if (!ParentDC->isDependentContext())
2207 return D;
2208
2209 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002210 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002211 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Douglas Gregor815215d2009-05-27 05:35:12 +00002213 if (ParentDC != D->getDeclContext()) {
2214 // We performed some kind of instantiation in the parent context,
2215 // so now we need to look into the instantiated parent context to
2216 // find the instantiation of the declaration D.
2217 NamedDecl *Result = 0;
2218 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002219 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002220 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2221 } else {
2222 // Since we don't have a name for the entity we're looking for,
2223 // our only option is to walk through all of the declarations to
2224 // find that name. This will occur in a few cases:
2225 //
2226 // - anonymous struct/union within a template
2227 // - unnamed class/struct/union/enum within a template
2228 //
2229 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002230 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002231 ParentDC->decls_begin(),
2232 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002233 }
Mike Stump1eb44332009-09-09 15:08:12 +00002234
John McCall9f54ad42009-12-10 09:41:52 +00002235 // UsingShadowDecls can instantiate to nothing because of using hiding.
2236 assert((Result || isa<UsingShadowDecl>(D))
2237 && "Unable to find instantiation of declaration!");
2238
Douglas Gregor815215d2009-05-27 05:35:12 +00002239 D = Result;
2240 }
2241
Douglas Gregor815215d2009-05-27 05:35:12 +00002242 return D;
2243}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002244
Mike Stump1eb44332009-09-09 15:08:12 +00002245/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002246/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002247void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2248 while (!PendingLocalImplicitInstantiations.empty() ||
2249 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2250 PendingImplicitInstantiation Inst;
2251
2252 if (PendingLocalImplicitInstantiations.empty()) {
2253 Inst = PendingImplicitInstantiations.front();
2254 PendingImplicitInstantiations.pop_front();
2255 } else {
2256 Inst = PendingLocalImplicitInstantiations.front();
2257 PendingLocalImplicitInstantiations.pop_front();
2258 }
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Douglas Gregor7caa6822009-07-24 20:34:43 +00002260 // Instantiate function definitions
2261 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002262 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002263 Function->getLocation(), *this,
2264 Context.getSourceManager(),
2265 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002267 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002268 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002269 continue;
2270 }
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Douglas Gregor7caa6822009-07-24 20:34:43 +00002272 // Instantiate static data member definitions.
2273 VarDecl *Var = cast<VarDecl>(Inst.first);
2274 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002275
Mike Stump1eb44332009-09-09 15:08:12 +00002276 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002277 Var->getLocation(), *this,
2278 Context.getSourceManager(),
2279 "instantiating static data member "
2280 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Douglas Gregor7caa6822009-07-24 20:34:43 +00002282 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002283 }
2284}