blob: 549f87b2cadba21c06f8b31b2af96b389a5b8f1c [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);
John McCall3dbd3d52010-02-16 06:53:13 +000046 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000048 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitFieldDecl(FieldDecl *D);
50 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
51 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000052 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000053 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000054 Decl *VisitFunctionDecl(FunctionDecl *D,
55 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000056 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000057 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
58 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000059 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000060 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000061 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000062 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000063 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000064 Decl *VisitClassTemplatePartialSpecializationDecl(
65 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000066 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000067 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000068 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000069 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000070 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000071 Decl *VisitUsingDecl(UsingDecl *D);
72 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000073 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
74 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor8dbc2692009-03-17 21:15:40 +000076 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000077 Decl *VisitDecl(Decl *D) {
78 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
79 Diagnostic::Error,
80 "cannot instantiate %0 yet");
81 SemaRef.Diag(D->getLocation(), DiagID)
82 << D->getDeclKindName();
83
Douglas Gregor8dbc2692009-03-17 21:15:40 +000084 return 0;
85 }
Douglas Gregor5545e162009-03-24 00:38:23 +000086
John McCallfd810b12009-08-14 02:03:10 +000087 const LangOptions &getLangOptions() {
88 return SemaRef.getLangOptions();
89 }
90
Douglas Gregor5545e162009-03-24 00:38:23 +000091 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000092 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000093 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000094 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000095 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000096
97 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000098 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000099
100 bool InstantiateClassTemplatePartialSpecialization(
101 ClassTemplateDecl *ClassTemplate,
102 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 };
104}
105
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000106// FIXME: Is this too simple?
107void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
108 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
109 TmplAttr = TmplAttr->getNext()) {
110
111 // FIXME: Is cloning correct for all attributes?
112 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
113
114 New->addAttr(NewAttr);
115 }
116}
117
Douglas Gregor4f722be2009-03-25 15:45:12 +0000118Decl *
119TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
120 assert(false && "Translation units cannot be instantiated");
121 return D;
122}
123
124Decl *
125TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
126 assert(false && "Namespaces cannot be instantiated");
127 return D;
128}
129
John McCall3dbd3d52010-02-16 06:53:13 +0000130Decl *
131TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
132 NamespaceAliasDecl *Inst
133 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
134 D->getNamespaceLoc(),
135 D->getAliasLoc(),
136 D->getNamespace()->getIdentifier(),
137 D->getQualifierRange(),
138 D->getQualifier(),
139 D->getTargetNameLoc(),
140 D->getNamespace());
141 Owner->addDecl(Inst);
142 return Inst;
143}
144
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
146 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000147 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000148 if (DI->getType()->isDependentType()) {
149 DI = SemaRef.SubstType(DI, TemplateArgs,
150 D->getLocation(), D->getDeclName());
151 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000152 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000153 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000154 }
155 }
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000157 // Create the new typedef
158 TypedefDecl *Typedef
159 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000160 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000161 if (Invalid)
162 Typedef->setInvalidDecl();
163
John McCall5126fd02009-12-30 00:31:22 +0000164 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000165 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
166 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000167 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
168 }
169
John McCall46460a62010-01-20 21:53:11 +0000170 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000171 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000173 return Typedef;
174}
175
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176/// \brief Instantiate the arguments provided as part of initialization.
177///
178/// \returns true if an error occurred, false otherwise.
179static bool InstantiateInitializationArguments(Sema &SemaRef,
180 Expr **Args, unsigned NumArgs,
181 const MultiLevelTemplateArgumentList &TemplateArgs,
182 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
183 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
184 for (unsigned I = 0; I != NumArgs; ++I) {
185 // When we hit the first defaulted argument, break out of the loop:
186 // we don't pass those default arguments on.
187 if (Args[I]->isDefaultArgument())
188 break;
189
190 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
191 if (Arg.isInvalid())
192 return true;
193
194 Expr *ArgExpr = (Expr *)Arg.get();
195 InitArgs.push_back(Arg.release());
196
197 // FIXME: We're faking all of the comma locations. Do we need them?
198 FakeCommaLocs.push_back(
199 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
200 }
201
202 return false;
203}
204
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000205Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000206 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000207 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000208 TemplateArgs,
209 D->getTypeSpecStartLoc(),
210 D->getDeclName());
211 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000212 return 0;
213
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000214 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000215 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
216 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000217 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000218 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000219 Var->setThreadSpecified(D->isThreadSpecified());
220 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
221 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000222
223 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000224 // out-of-line, the instantiation will have the same lexical
225 // context (which will be a namespace scope) as the template.
226 if (D->isOutOfLine())
227 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000228
John McCall46460a62010-01-20 21:53:11 +0000229 Var->setAccess(D->getAccess());
230
Mike Stump390b4cc2009-05-16 07:39:55 +0000231 // FIXME: In theory, we could have a previous declaration for variables that
232 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000233 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000234 // FIXME: having to fake up a LookupResult is dumb.
235 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000236 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000237 if (D->isStaticDataMember())
238 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000239 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Douglas Gregor7caa6822009-07-24 20:34:43 +0000241 if (D->isOutOfLine()) {
242 D->getLexicalDeclContext()->addDecl(Var);
243 Owner->makeDeclVisibleInContext(Var);
244 } else {
245 Owner->addDecl(Var);
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000248 // Link instantiations of static data members back to the template from
249 // which they were instantiated.
250 if (Var->isStaticDataMember())
251 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000252 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000253
Douglas Gregor60c93c92010-02-09 07:26:29 +0000254 if (Var->getAnyInitializer()) {
255 // We already have an initializer in the class.
256 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000257 if (Var->isStaticDataMember() && !D->isOutOfLine())
258 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
259 else
260 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
261
Douglas Gregor6eef5192009-12-14 19:27:10 +0000262 // Extract the initializer, skipping through any temporary-binding
263 // expressions and look at the subexpression as it was written.
264 Expr *DInit = D->getInit();
Douglas Gregora89ebea2010-02-03 09:01:59 +0000265 if (CXXExprWithTemporaries *ExprTemp
266 = dyn_cast<CXXExprWithTemporaries>(DInit))
267 DInit = ExprTemp->getSubExpr();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000268 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
269 DInit = Binder->getSubExpr();
270 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
271 DInit = ICE->getSubExprAsWritten();
272
273 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
274 // The initializer is a parenthesized list of expressions that is
275 // type-dependent. Instantiate each of the expressions; we'll be
276 // performing direct initialization with them.
277 llvm::SmallVector<SourceLocation, 4> CommaLocs;
278 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
279 if (!InstantiateInitializationArguments(SemaRef,
280 PLE->getExprs(),
281 PLE->getNumExprs(),
282 TemplateArgs,
283 CommaLocs, InitArgs)) {
284 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000285 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000286 PLE->getLParenLoc(),
287 move_arg(InitArgs),
288 CommaLocs.data(),
289 PLE->getRParenLoc());
290 }
291 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
292 // The initializer resolved to a constructor. Instantiate the constructor
293 // arguments.
294 llvm::SmallVector<SourceLocation, 4> CommaLocs;
295 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
296
297 if (!InstantiateInitializationArguments(SemaRef,
298 Construct->getArgs(),
299 Construct->getNumArgs(),
300 TemplateArgs,
301 CommaLocs, InitArgs)) {
302 if (D->hasCXXDirectInitializer()) {
303 SourceLocation FakeLParenLoc =
304 SemaRef.PP.getLocForEndOfToken(D->getLocation());
305 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
306 : CommaLocs.back();
307 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
308 FakeLParenLoc,
309 move_arg(InitArgs),
310 CommaLocs.data(),
311 FakeRParenLoc);
312 } else if (InitArgs.size() == 1) {
313 Expr *Init = (Expr*)(InitArgs.take()[0]);
314 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
315 SemaRef.Owned(Init),
316 false);
317 } else {
318 assert(InitArgs.size() == 0);
319 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
320 }
321 }
322 } else {
323 OwningExprResult Init
324 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
325
326 // FIXME: Not happy about invalidating decls just because of a bad
327 // initializer, unless it affects the type.
328 if (Init.isInvalid())
329 Var->setInvalidDecl();
330 else
331 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
332 D->hasCXXDirectInitializer());
333 }
334
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000335 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000336 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
337 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000338
339 return Var;
340}
341
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000342Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
343 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000344 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000345 if (DI->getType()->isDependentType()) {
346 DI = SemaRef.SubstType(DI, TemplateArgs,
347 D->getLocation(), D->getDeclName());
348 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000349 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000350 Invalid = true;
351 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000352 // C++ [temp.arg.type]p3:
353 // If a declaration acquires a function type through a type
354 // dependent on a template-parameter and this causes a
355 // declaration that does not use the syntactic form of a
356 // function declarator to have function type, the program is
357 // ill-formed.
358 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000359 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000360 Invalid = true;
361 }
362 }
363
364 Expr *BitWidth = D->getBitWidth();
365 if (Invalid)
366 BitWidth = 0;
367 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000368 // The bit-width expression is not potentially evaluated.
369 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000372 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000373 if (InstantiatedBitWidth.isInvalid()) {
374 Invalid = true;
375 BitWidth = 0;
376 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000377 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378 }
379
John McCall07fb6be2009-10-22 23:33:21 +0000380 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
381 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000382 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383 D->getLocation(),
384 D->isMutable(),
385 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000386 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000387 D->getAccess(),
388 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000389 if (!Field) {
390 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000391 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000394 InstantiateAttrs(D, Field);
395
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000396 if (Invalid)
397 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000399 if (!Field->getDeclName()) {
400 // Keep track of where this decl came from.
401 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000404 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000405 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000406 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407
408 return Field;
409}
410
John McCall02cace72009-08-28 07:59:38 +0000411Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
412 FriendDecl::FriendUnion FU;
413
414 // Handle friend type expressions by simply substituting template
415 // parameters into the pattern type.
416 if (Type *Ty = D->getFriendType()) {
417 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
418 D->getLocation(), DeclarationName());
419 if (T.isNull()) return 0;
420
421 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
422 FU = T.getTypePtr();
423
424 // Handle everything else by appropriate substitution.
425 } else {
426 NamedDecl *ND = D->getFriendDecl();
427 assert(ND && "friend decl must be a decl or a type!");
428
Douglas Gregora735b202009-10-13 14:39:41 +0000429 // FIXME: We have a problem here, because the nested call to Visit(ND)
430 // will inject the thing that the friend references into the current
431 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000432 Decl *NewND;
433
434 // Hack to make this work almost well pending a rewrite.
Douglas Gregor63644fa2010-02-07 10:31:35 +0000435 if (ND->getDeclContext()->isRecord()) {
436 if (!ND->getDeclContext()->isDependentContext()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000437 NewND = SemaRef.FindInstantiatedDecl(D->getLocation(), ND,
438 TemplateArgs);
Douglas Gregor63644fa2010-02-07 10:31:35 +0000439 } else {
440 // FIXME: Hack to avoid crashing when incorrectly trying to instantiate
441 // templated friend declarations. This doesn't produce a correct AST;
442 // however this is sufficient for some AST analysis. The real solution
443 // must be put in place during the pending rewrite. See PR5848.
444 return 0;
445 }
446 } else if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000447 // Totally egregious hack to work around PR5866
448 return 0;
449 } else
John McCalle129d442009-12-17 23:21:11 +0000450 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000451 if (!NewND) return 0;
452
453 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
John McCall02cace72009-08-28 07:59:38 +0000456 FriendDecl *FD =
457 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
458 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000459 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000460 Owner->addDecl(FD);
461 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000462}
463
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
465 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Douglas Gregorac7610d2009-06-22 20:57:11 +0000467 // The expression in a static assertion is not potentially evaluated.
468 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000470 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000471 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 if (InstantiatedAssertExpr.isInvalid())
473 return 0;
474
Douglas Gregor43d9d922009-08-08 01:41:12 +0000475 OwningExprResult Message(SemaRef, D->getMessage());
476 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000477 Decl *StaticAssert
478 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 move(InstantiatedAssertExpr),
480 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 return StaticAssert;
482}
483
484Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000485 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000486 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000487 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000489 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000490 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000492 Enum->startDefinition();
493
Douglas Gregor96084f12010-03-01 19:00:07 +0000494 if (D->getDeclContext()->isFunctionOrMethod())
495 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
496
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000497 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000498
499 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000500 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
501 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000502 EC != ECEnd; ++EC) {
503 // The specified value for the enumerator.
504 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000505 if (Expr *UninstValue = EC->getInitExpr()) {
506 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000507 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000508 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
John McCallce3ff2b2009-08-25 22:02:44 +0000510 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000511 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000512
513 // Drop the initial value and continue.
514 bool isInvalid = false;
515 if (Value.isInvalid()) {
516 Value = SemaRef.Owned((Expr *)0);
517 isInvalid = true;
518 }
519
Mike Stump1eb44332009-09-09 15:08:12 +0000520 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000521 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
522 EC->getLocation(), EC->getIdentifier(),
523 move(Value));
524
525 if (isInvalid) {
526 if (EnumConst)
527 EnumConst->setInvalidDecl();
528 Enum->setInvalidDecl();
529 }
530
531 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000532 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000533 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000534 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000536
537 if (D->getDeclContext()->isFunctionOrMethod()) {
538 // If the enumeration is within a function or method, record the enum
539 // constant as a local.
540 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
541 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542 }
543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000545 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000546 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000547 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
548 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000549 &Enumerators[0], Enumerators.size(),
550 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000551
552 return Enum;
553}
554
Douglas Gregor6477b692009-03-25 15:04:13 +0000555Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
556 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
557 return 0;
558}
559
Douglas Gregored9c0f92009-10-29 00:04:11 +0000560namespace {
561 class SortDeclByLocation {
562 SourceManager &SourceMgr;
563
564 public:
565 explicit SortDeclByLocation(SourceManager &SourceMgr)
566 : SourceMgr(SourceMgr) { }
567
568 bool operator()(const Decl *X, const Decl *Y) const {
569 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
570 Y->getLocation());
571 }
572 };
573}
574
John McCalle29ba202009-08-20 01:44:21 +0000575Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000576 // Create a local instantiation scope for this class template, which
577 // will contain the instantiations of the template parameters.
578 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000579 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000580 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000581 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000582 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000583
584 CXXRecordDecl *Pattern = D->getTemplatedDecl();
585 CXXRecordDecl *RecordInst
586 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
587 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000588 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
589 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000590
591 ClassTemplateDecl *Inst
592 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
593 D->getIdentifier(), InstParams, RecordInst, 0);
594 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000595 if (D->getFriendObjectKind())
596 Inst->setObjectOfFriendDecl(true);
597 else
598 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000599 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000600
601 // Trigger creation of the type for the instantiation.
602 SemaRef.Context.getTypeDeclType(RecordInst);
603
Douglas Gregor259571e2009-10-30 22:42:42 +0000604 // Finish handling of friends.
605 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000606 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000607 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000608
John McCall46460a62010-01-20 21:53:11 +0000609 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000610 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000611
612 // First, we sort the partial specializations by location, so
613 // that we instantiate them in the order they were declared.
614 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
615 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
616 P = D->getPartialSpecializations().begin(),
617 PEnd = D->getPartialSpecializations().end();
618 P != PEnd; ++P)
619 PartialSpecs.push_back(&*P);
620 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
621 SortDeclByLocation(SemaRef.SourceMgr));
622
623 // Instantiate all of the partial specializations of this member class
624 // template.
625 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
626 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
627
John McCalle29ba202009-08-20 01:44:21 +0000628 return Inst;
629}
630
Douglas Gregord60e1052009-08-27 16:57:43 +0000631Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000632TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
633 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000634 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
635
636 // Lookup the already-instantiated declaration in the instantiation
637 // of the class template and return that.
638 DeclContext::lookup_result Found
639 = Owner->lookup(ClassTemplate->getDeclName());
640 if (Found.first == Found.second)
641 return 0;
642
643 ClassTemplateDecl *InstClassTemplate
644 = dyn_cast<ClassTemplateDecl>(*Found.first);
645 if (!InstClassTemplate)
646 return 0;
647
648 Decl *DCanon = D->getCanonicalDecl();
649 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
650 P = InstClassTemplate->getPartialSpecializations().begin(),
651 PEnd = InstClassTemplate->getPartialSpecializations().end();
652 P != PEnd; ++P) {
653 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
654 return &*P;
655 }
656
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000657 return 0;
658}
659
660Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000661TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000662 // Create a local instantiation scope for this function template, which
663 // will contain the instantiations of the template parameters and then get
664 // merged with the local instantiation scope for the function template
665 // itself.
666 Sema::LocalInstantiationScope Scope(SemaRef);
667
Douglas Gregord60e1052009-08-27 16:57:43 +0000668 TemplateParameterList *TempParams = D->getTemplateParameters();
669 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000670 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000671 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000672
Douglas Gregora735b202009-10-13 14:39:41 +0000673 FunctionDecl *Instantiated = 0;
674 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
675 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
676 InstParams));
677 else
678 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
679 D->getTemplatedDecl(),
680 InstParams));
681
682 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000683 return 0;
684
John McCall46460a62010-01-20 21:53:11 +0000685 Instantiated->setAccess(D->getAccess());
686
Mike Stump1eb44332009-09-09 15:08:12 +0000687 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000688 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000689 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000690 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000691 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000692 assert(InstTemplate &&
693 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000694
695 // Link the instantiation back to the pattern *unless* this is a
696 // non-definition friend declaration.
697 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
698 !(InstTemplate->getFriendObjectKind() &&
699 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000700 InstTemplate->setInstantiatedFromMemberTemplate(D);
701
702 // Add non-friends into the owner.
703 if (!InstTemplate->getFriendObjectKind())
704 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000705 return InstTemplate;
706}
707
Douglas Gregord475b8d2009-03-25 21:17:03 +0000708Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
709 CXXRecordDecl *PrevDecl = 0;
710 if (D->isInjectedClassName())
711 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000712 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000713 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
714 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000715 TemplateArgs);
716 if (!Prev) return 0;
717 PrevDecl = cast<CXXRecordDecl>(Prev);
718 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000719
720 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000721 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000722 D->getLocation(), D->getIdentifier(),
723 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000724 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000725 // FIXME: Check against AS_none is an ugly hack to work around the issue that
726 // the tag decls introduced by friend class declarations don't have an access
727 // specifier. Remove once this area of the code gets sorted out.
728 if (D->getAccess() != AS_none)
729 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000730 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000731 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000732
John McCall02cace72009-08-28 07:59:38 +0000733 // If the original function was part of a friend declaration,
734 // inherit its namespace state.
735 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
736 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
737
Anders Carlssond8b285f2009-09-01 04:26:58 +0000738 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
739
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000740 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000741 return Record;
742}
743
John McCall02cace72009-08-28 07:59:38 +0000744/// Normal class members are of more specific types and therefore
745/// don't make it here. This function serves two purposes:
746/// 1) instantiating function templates
747/// 2) substituting friend declarations
748/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000749Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000750 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000751 // Check whether there is already a function template specialization for
752 // this declaration.
753 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
754 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000755 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000756 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000757 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000758 TemplateArgs.getInnermost().getFlatArgumentList(),
759 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000760 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
762 FunctionTemplateSpecializationInfo *Info
763 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000764 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregor127102b2009-06-29 20:59:39 +0000766 // If we already have a function template specialization, return it.
767 if (Info)
768 return Info->Function;
769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Douglas Gregor79c22782010-01-16 20:21:20 +0000771 bool MergeWithParentScope = (TemplateParams != 0) ||
772 !(isa<Decl>(Owner) &&
773 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
774 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Douglas Gregore53060f2009-06-25 22:08:12 +0000776 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000777 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000778 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000779 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000780
John McCall68b6b872010-02-06 01:50:47 +0000781 // If we're instantiating a local function declaration, put the result
782 // in the owner; otherwise we need to find the instantiated context.
783 DeclContext *DC;
784 if (D->getDeclContext()->isFunctionOrMethod())
785 DC = Owner;
786 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000787 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
788 TemplateArgs);
John McCall68b6b872010-02-06 01:50:47 +0000789
John McCall02cace72009-08-28 07:59:38 +0000790 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000791 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000792 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000793 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000794 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000795 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Douglas Gregore53060f2009-06-25 22:08:12 +0000797 // Attach the parameters
798 for (unsigned P = 0; P < Params.size(); ++P)
799 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000800 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000801
Douglas Gregora735b202009-10-13 14:39:41 +0000802 if (TemplateParams) {
803 // Our resulting instantiation is actually a function template, since we
804 // are substituting only the outer template parameters. For example, given
805 //
806 // template<typename T>
807 // struct X {
808 // template<typename U> friend void f(T, U);
809 // };
810 //
811 // X<int> x;
812 //
813 // We are instantiating the friend function template "f" within X<int>,
814 // which means substituting int for T, but leaving "f" as a friend function
815 // template.
816 // Build the function template itself.
817 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
818 Function->getLocation(),
819 Function->getDeclName(),
820 TemplateParams, Function);
821 Function->setDescribedFunctionTemplate(FunctionTemplate);
822 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000823 } else if (FunctionTemplate) {
824 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000825 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000826 &TemplateArgs.getInnermost(),
827 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000828 }
Douglas Gregora735b202009-10-13 14:39:41 +0000829
Douglas Gregore53060f2009-06-25 22:08:12 +0000830 if (InitFunctionInstantiation(Function, D))
831 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregore53060f2009-06-25 22:08:12 +0000833 bool Redeclaration = false;
834 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000835
John McCall68263142009-11-18 22:49:29 +0000836 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
837 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
838
Douglas Gregora735b202009-10-13 14:39:41 +0000839 if (TemplateParams || !FunctionTemplate) {
840 // Look only into the namespace where the friend would be declared to
841 // find a previous declaration. This is the innermost enclosing namespace,
842 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000843 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000844
Douglas Gregora735b202009-10-13 14:39:41 +0000845 // In C++, the previous declaration we find might be a tag type
846 // (class or enum). In this case, the new declaration will hide the
847 // tag type. Note that this does does not apply if we're declaring a
848 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000849 if (Previous.isSingleTagDecl())
850 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000851 }
852
John McCall9f54ad42009-12-10 09:41:52 +0000853 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
854 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000855 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000856
Douglas Gregora735b202009-10-13 14:39:41 +0000857 // If the original function was part of a friend declaration,
858 // inherit its namespace state and add it to the owner.
859 NamedDecl *FromFriendD
860 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
861 if (FromFriendD->getFriendObjectKind()) {
862 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000863 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000864 if (TemplateParams) {
865 ToFriendD = cast<NamedDecl>(FunctionTemplate);
866 PrevDecl = FunctionTemplate->getPreviousDeclaration();
867 } else {
868 ToFriendD = Function;
869 PrevDecl = Function->getPreviousDeclaration();
870 }
871 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
872 if (!Owner->isDependentContext() && !PrevDecl)
873 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
874
875 if (!TemplateParams)
876 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
877 }
878
Douglas Gregore53060f2009-06-25 22:08:12 +0000879 return Function;
880}
881
Douglas Gregord60e1052009-08-27 16:57:43 +0000882Decl *
883TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
884 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000885 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
886 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000887 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000888 // We are creating a function template specialization from a function
889 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000890 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000891 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000892 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000893 TemplateArgs.getInnermost().getFlatArgumentList(),
894 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000895 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
897 FunctionTemplateSpecializationInfo *Info
898 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000899 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregor6b906862009-08-21 00:16:32 +0000901 // If we already have a function template specialization, return it.
902 if (Info)
903 return Info->Function;
904 }
905
Douglas Gregor79c22782010-01-16 20:21:20 +0000906 bool MergeWithParentScope = (TemplateParams != 0) ||
907 !(isa<Decl>(Owner) &&
908 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
909 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000910
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000911 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000912 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000913 if (T.isNull())
914 return 0;
915
916 // Build the instantiated method declaration.
917 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000918 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregordec06662009-08-21 18:42:58 +0000920 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000921 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000922 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
923 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
924 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000925 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
926 Constructor->getLocation(),
927 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000928 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000929 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000930 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000931 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
932 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
933 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
934 SemaRef.Context.getCanonicalType(ClassTy));
935 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
936 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000937 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000938 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000939 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000940 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000941 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000942 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
943 ConvTy);
944 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
945 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000946 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000947 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000948 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000949 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000950 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000951 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000952 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000953 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000954
Douglas Gregord60e1052009-08-27 16:57:43 +0000955 if (TemplateParams) {
956 // Our resulting instantiation is actually a function template, since we
957 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000958 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000959 // template<typename T>
960 // struct X {
961 // template<typename U> void f(T, U);
962 // };
963 //
964 // X<int> x;
965 //
966 // We are instantiating the member template "f" within X<int>, which means
967 // substituting int for T, but leaving "f" as a member function template.
968 // Build the function template itself.
969 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
970 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000971 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000972 TemplateParams, Method);
973 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000974 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000975 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000976 } else if (FunctionTemplate) {
977 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000978 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000979 &TemplateArgs.getInnermost(),
980 InsertPos);
981 } else {
982 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000983 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000984 }
985
Mike Stump1eb44332009-09-09 15:08:12 +0000986 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000987 // out-of-line, the instantiation will have the same lexical
988 // context (which will be a namespace scope) as the template.
989 if (D->isOutOfLine())
990 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Douglas Gregor5545e162009-03-24 00:38:23 +0000992 // Attach the parameters
993 for (unsigned P = 0; P < Params.size(); ++P)
994 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +0000995 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000996
997 if (InitMethodInstantiation(Method, D))
998 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000999
John McCall68263142009-11-18 22:49:29 +00001000 LookupResult Previous(SemaRef, Name, SourceLocation(),
1001 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Douglas Gregord60e1052009-08-27 16:57:43 +00001003 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +00001004 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Douglas Gregordec06662009-08-21 18:42:58 +00001006 // In C++, the previous declaration we find might be a tag type
1007 // (class or enum). In this case, the new declaration will hide the
1008 // tag type. Note that this does does not apply if we're declaring a
1009 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001010 if (Previous.isSingleTagDecl())
1011 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001012 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001013
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001014 bool Redeclaration = false;
1015 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001016 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001017 /*FIXME:*/OverloadableAttrRequired);
1018
Douglas Gregor4ba31362009-12-01 17:24:26 +00001019 if (D->isPure())
1020 SemaRef.CheckPureMethod(Method, SourceRange());
1021
John McCall46460a62010-01-20 21:53:11 +00001022 Method->setAccess(D->getAccess());
1023
John McCall68263142009-11-18 22:49:29 +00001024 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +00001025 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +00001026 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001028 return Method;
1029}
1030
Douglas Gregor615c5d42009-03-24 16:43:20 +00001031Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001032 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001033}
1034
Douglas Gregor03b2b072009-03-24 00:15:49 +00001035Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001036 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001037}
1038
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001039Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001040 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001041}
1042
Douglas Gregor6477b692009-03-25 15:04:13 +00001043ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001044 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001045 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001046 if (DI) {
1047 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1048 D->getDeclName());
1049 if (DI) T = DI->getType();
1050 } else {
1051 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1052 D->getDeclName());
1053 DI = 0;
1054 }
1055
1056 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001057 return 0;
1058
John McCall58e46772009-10-23 21:48:59 +00001059 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001060
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001061 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001062 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001063 = ParmVarDecl::Create(SemaRef.Context,
1064 SemaRef.Context.getTranslationUnitDecl(),
1065 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001066 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001067
Anders Carlsson9351c172009-08-25 03:18:48 +00001068 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001069 if (D->hasUninstantiatedDefaultArg())
1070 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001071 else if (Expr *Arg = D->getDefaultArg())
1072 Param->setUninstantiatedDefaultArg(Arg);
1073
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001074 // Note: we don't try to instantiate function parameters until after
1075 // we've instantiated the function's type. Therefore, we don't have
1076 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001077 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001078 return Param;
1079}
1080
John McCalle29ba202009-08-20 01:44:21 +00001081Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1082 TemplateTypeParmDecl *D) {
1083 // TODO: don't always clone when decls are refcounted.
1084 const Type* T = D->getTypeForDecl();
1085 assert(T->isTemplateTypeParmType());
1086 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
John McCalle29ba202009-08-20 01:44:21 +00001088 TemplateTypeParmDecl *Inst =
1089 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001090 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001091 TTPT->getName(),
1092 D->wasDeclaredWithTypename(),
1093 D->isParameterPack());
1094
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001095 if (D->hasDefaultArgument())
1096 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001097
Douglas Gregor550d9b22009-10-31 17:21:17 +00001098 // Introduce this template parameter's instantiation into the instantiation
1099 // scope.
1100 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1101
John McCalle29ba202009-08-20 01:44:21 +00001102 return Inst;
1103}
1104
Douglas Gregor33642df2009-10-23 23:25:44 +00001105Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1106 NonTypeTemplateParmDecl *D) {
1107 // Substitute into the type of the non-type template parameter.
1108 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001109 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001110 if (DI) {
1111 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1112 D->getDeclName());
1113 if (DI) T = DI->getType();
1114 } else {
1115 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1116 D->getDeclName());
1117 DI = 0;
1118 }
1119 if (T.isNull())
1120 return 0;
1121
1122 // Check that this type is acceptable for a non-type template parameter.
1123 bool Invalid = false;
1124 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1125 if (T.isNull()) {
1126 T = SemaRef.Context.IntTy;
1127 Invalid = true;
1128 }
1129
1130 NonTypeTemplateParmDecl *Param
1131 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1132 D->getDepth() - 1, D->getPosition(),
1133 D->getIdentifier(), T, DI);
1134 if (Invalid)
1135 Param->setInvalidDecl();
1136
1137 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001138
1139 // Introduce this template parameter's instantiation into the instantiation
1140 // scope.
1141 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001142 return Param;
1143}
1144
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001145Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001146TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1147 TemplateTemplateParmDecl *D) {
1148 // Instantiate the template parameter list of the template template parameter.
1149 TemplateParameterList *TempParams = D->getTemplateParameters();
1150 TemplateParameterList *InstParams;
1151 {
1152 // Perform the actual substitution of template parameters within a new,
1153 // local instantiation scope.
1154 Sema::LocalInstantiationScope Scope(SemaRef);
1155 InstParams = SubstTemplateParams(TempParams);
1156 if (!InstParams)
1157 return NULL;
1158 }
1159
1160 // Build the template template parameter.
1161 TemplateTemplateParmDecl *Param
1162 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1163 D->getDepth() - 1, D->getPosition(),
1164 D->getIdentifier(), InstParams);
1165 Param->setDefaultArgument(D->getDefaultArgument());
1166
1167 // Introduce this template parameter's instantiation into the instantiation
1168 // scope.
1169 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1170
1171 return Param;
1172}
1173
Douglas Gregor48c32a72009-11-17 06:07:40 +00001174Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1175 // Using directives are never dependent, so they require no explicit
1176
1177 UsingDirectiveDecl *Inst
1178 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1179 D->getNamespaceKeyLocation(),
1180 D->getQualifierRange(), D->getQualifier(),
1181 D->getIdentLocation(),
1182 D->getNominatedNamespace(),
1183 D->getCommonAncestor());
1184 Owner->addDecl(Inst);
1185 return Inst;
1186}
1187
John McCalled976492009-12-04 22:46:56 +00001188Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1189 // The nested name specifier is non-dependent, so no transformation
1190 // is required.
1191
John McCall9f54ad42009-12-10 09:41:52 +00001192 // We only need to do redeclaration lookups if we're in a class
1193 // scope (in fact, it's not really even possible in non-class
1194 // scopes).
1195 bool CheckRedeclaration = Owner->isRecord();
1196
1197 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1198 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1199
John McCalled976492009-12-04 22:46:56 +00001200 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1201 D->getLocation(),
1202 D->getNestedNameRange(),
1203 D->getUsingLocation(),
1204 D->getTargetNestedNameDecl(),
1205 D->getDeclName(),
1206 D->isTypeName());
1207
1208 CXXScopeSpec SS;
1209 SS.setScopeRep(D->getTargetNestedNameDecl());
1210 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001211
1212 if (CheckRedeclaration) {
1213 Prev.setHideTags(false);
1214 SemaRef.LookupQualifiedName(Prev, Owner);
1215
1216 // Check for invalid redeclarations.
1217 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1218 D->isTypeName(), SS,
1219 D->getLocation(), Prev))
1220 NewUD->setInvalidDecl();
1221
1222 }
1223
1224 if (!NewUD->isInvalidDecl() &&
1225 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001226 D->getLocation()))
1227 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001228
John McCalled976492009-12-04 22:46:56 +00001229 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1230 NewUD->setAccess(D->getAccess());
1231 Owner->addDecl(NewUD);
1232
John McCall9f54ad42009-12-10 09:41:52 +00001233 // Don't process the shadow decls for an invalid decl.
1234 if (NewUD->isInvalidDecl())
1235 return NewUD;
1236
John McCall323c3102009-12-22 22:26:37 +00001237 bool isFunctionScope = Owner->isFunctionOrMethod();
1238
John McCall9f54ad42009-12-10 09:41:52 +00001239 // Process the shadow decls.
1240 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1241 I != E; ++I) {
1242 UsingShadowDecl *Shadow = *I;
1243 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001244 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1245 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001246 TemplateArgs));
1247
1248 if (CheckRedeclaration &&
1249 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1250 continue;
1251
1252 UsingShadowDecl *InstShadow
1253 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1254 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001255
1256 if (isFunctionScope)
1257 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001258 }
John McCalled976492009-12-04 22:46:56 +00001259
1260 return NewUD;
1261}
1262
1263Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001264 // Ignore these; we handle them in bulk when processing the UsingDecl.
1265 return 0;
John McCalled976492009-12-04 22:46:56 +00001266}
1267
John McCall7ba107a2009-11-18 02:36:19 +00001268Decl * TemplateDeclInstantiator
1269 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001270 NestedNameSpecifier *NNS =
1271 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1272 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001273 TemplateArgs);
1274 if (!NNS)
1275 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001277 CXXScopeSpec SS;
1278 SS.setRange(D->getTargetNestedNameRange());
1279 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
1281 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001282 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001283 D->getUsingLoc(), SS, D->getLocation(),
1284 D->getDeclName(), 0,
1285 /*instantiation*/ true,
1286 /*typename*/ true, D->getTypenameLoc());
1287 if (UD)
John McCalled976492009-12-04 22:46:56 +00001288 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1289
John McCall7ba107a2009-11-18 02:36:19 +00001290 return UD;
1291}
1292
1293Decl * TemplateDeclInstantiator
1294 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1295 NestedNameSpecifier *NNS =
1296 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1297 D->getTargetNestedNameRange(),
1298 TemplateArgs);
1299 if (!NNS)
1300 return 0;
1301
1302 CXXScopeSpec SS;
1303 SS.setRange(D->getTargetNestedNameRange());
1304 SS.setScopeRep(NNS);
1305
1306 NamedDecl *UD =
1307 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1308 D->getUsingLoc(), SS, D->getLocation(),
1309 D->getDeclName(), 0,
1310 /*instantiation*/ true,
1311 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001312 if (UD)
John McCalled976492009-12-04 22:46:56 +00001313 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1314
Anders Carlsson0d8df782009-08-29 19:37:28 +00001315 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001316}
1317
John McCallce3ff2b2009-08-25 22:02:44 +00001318Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001319 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001320 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001321 if (D->isInvalidDecl())
1322 return 0;
1323
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001324 return Instantiator.Visit(D);
1325}
1326
John McCalle29ba202009-08-20 01:44:21 +00001327/// \brief Instantiates a nested template parameter list in the current
1328/// instantiation context.
1329///
1330/// \param L The parameter list to instantiate
1331///
1332/// \returns NULL if there was an error
1333TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001334TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001335 // Get errors for all the parameters before bailing out.
1336 bool Invalid = false;
1337
1338 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001339 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001340 ParamVector Params;
1341 Params.reserve(N);
1342 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1343 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001344 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001345 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001346 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001347 }
1348
1349 // Clean up if we had an error.
1350 if (Invalid) {
1351 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1352 PI != PE; ++PI)
1353 if (*PI)
1354 (*PI)->Destroy(SemaRef.Context);
1355 return NULL;
1356 }
1357
1358 TemplateParameterList *InstL
1359 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1360 L->getLAngleLoc(), &Params.front(), N,
1361 L->getRAngleLoc());
1362 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001363}
John McCalle29ba202009-08-20 01:44:21 +00001364
Douglas Gregored9c0f92009-10-29 00:04:11 +00001365/// \brief Instantiate the declaration of a class template partial
1366/// specialization.
1367///
1368/// \param ClassTemplate the (instantiated) class template that is partially
1369// specialized by the instantiation of \p PartialSpec.
1370///
1371/// \param PartialSpec the (uninstantiated) class template partial
1372/// specialization that we are instantiating.
1373///
1374/// \returns true if there was an error, false otherwise.
1375bool
1376TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1377 ClassTemplateDecl *ClassTemplate,
1378 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001379 // Create a local instantiation scope for this class template partial
1380 // specialization, which will contain the instantiations of the template
1381 // parameters.
1382 Sema::LocalInstantiationScope Scope(SemaRef);
1383
Douglas Gregored9c0f92009-10-29 00:04:11 +00001384 // Substitute into the template parameters of the class template partial
1385 // specialization.
1386 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1387 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1388 if (!InstParams)
1389 return true;
1390
1391 // Substitute into the template arguments of the class template partial
1392 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001393 const TemplateArgumentLoc *PartialSpecTemplateArgs
1394 = PartialSpec->getTemplateArgsAsWritten();
1395 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1396
John McCalld5532b62009-11-23 01:53:49 +00001397 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001398 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001399 TemplateArgumentLoc Loc;
1400 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001401 return true;
John McCalld5532b62009-11-23 01:53:49 +00001402 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001403 }
1404
1405
1406 // Check that the template argument list is well-formed for this
1407 // class template.
1408 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1409 InstTemplateArgs.size());
1410 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1411 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001412 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001413 false,
1414 Converted))
1415 return true;
1416
1417 // Figure out where to insert this class template partial specialization
1418 // in the member template's set of class template partial specializations.
1419 llvm::FoldingSetNodeID ID;
1420 ClassTemplatePartialSpecializationDecl::Profile(ID,
1421 Converted.getFlatArguments(),
1422 Converted.flatSize(),
1423 SemaRef.Context);
1424 void *InsertPos = 0;
1425 ClassTemplateSpecializationDecl *PrevDecl
1426 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1427 InsertPos);
1428
1429 // Build the canonical type that describes the converted template
1430 // arguments of the class template partial specialization.
1431 QualType CanonType
1432 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1433 Converted.getFlatArguments(),
1434 Converted.flatSize());
1435
1436 // Build the fully-sugared type for this class template
1437 // specialization as the user wrote in the specialization
1438 // itself. This means that we'll pretty-print the type retrieved
1439 // from the specialization's declaration the way that the user
1440 // actually wrote the specialization, rather than formatting the
1441 // name based on the "canonical" representation used to store the
1442 // template arguments in the specialization.
1443 QualType WrittenTy
1444 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001445 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001446 CanonType);
1447
1448 if (PrevDecl) {
1449 // We've already seen a partial specialization with the same template
1450 // parameters and template arguments. This can happen, for example, when
1451 // substituting the outer template arguments ends up causing two
1452 // class template partial specializations of a member class template
1453 // to have identical forms, e.g.,
1454 //
1455 // template<typename T, typename U>
1456 // struct Outer {
1457 // template<typename X, typename Y> struct Inner;
1458 // template<typename Y> struct Inner<T, Y>;
1459 // template<typename Y> struct Inner<U, Y>;
1460 // };
1461 //
1462 // Outer<int, int> outer; // error: the partial specializations of Inner
1463 // // have the same signature.
1464 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1465 << WrittenTy;
1466 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1467 << SemaRef.Context.getTypeDeclType(PrevDecl);
1468 return true;
1469 }
1470
1471
1472 // Create the class template partial specialization declaration.
1473 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1474 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1475 PartialSpec->getLocation(),
1476 InstParams,
1477 ClassTemplate,
1478 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001479 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001480 0);
1481 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1482 InstPartialSpec->setTypeAsWritten(WrittenTy);
1483
1484 // Add this partial specialization to the set of class template partial
1485 // specializations.
1486 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1487 InsertPos);
1488 return false;
1489}
1490
John McCallce3ff2b2009-08-25 22:02:44 +00001491/// \brief Does substitution on the type of the given function, including
1492/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001493///
John McCallce3ff2b2009-08-25 22:02:44 +00001494/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001495///
1496/// \param Params the instantiated parameter declarations
1497
John McCallce3ff2b2009-08-25 22:02:44 +00001498/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001499/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001500QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001501TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001502 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1503 bool InvalidDecl = false;
1504
John McCallce3ff2b2009-08-25 22:02:44 +00001505 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001506 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001507 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001508 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001509 PEnd = D->param_end();
1510 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001511 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001512 if (PInst->getType()->isVoidType()) {
1513 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1514 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001515 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001516 PInst->getType(),
1517 diag::err_abstract_type_in_decl,
1518 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001519 PInst->setInvalidDecl();
1520
1521 Params.push_back(PInst);
1522 ParamTys.push_back(PInst->getType());
1523
1524 if (PInst->isInvalidDecl())
1525 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001526 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001527 InvalidDecl = true;
1528 }
1529
1530 // FIXME: Deallocate dead declarations.
1531 if (InvalidDecl)
1532 return QualType();
1533
John McCall183700f2009-09-21 23:43:11 +00001534 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001535 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001536 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001537 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1538 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001539 if (ResultType.isNull())
1540 return QualType();
1541
Jay Foadbeaaccd2009-05-21 09:52:38 +00001542 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001543 Proto->isVariadic(), Proto->getTypeQuals(),
1544 D->getLocation(), D->getDeclName());
1545}
1546
Mike Stump1eb44332009-09-09 15:08:12 +00001547/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001548/// declaration (New) from the corresponding fields of its template (Tmpl).
1549///
1550/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001551bool
1552TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001553 FunctionDecl *Tmpl) {
1554 if (Tmpl->isDeleted())
1555 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Douglas Gregorcca9e962009-07-01 22:01:06 +00001557 // If we are performing substituting explicitly-specified template arguments
1558 // or deduced template arguments into a function template and we reach this
1559 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // to keeping the new function template specialization. We therefore
1561 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001562 // into a template instantiation for this specific function template
1563 // specialization, which is not a SFINAE context, so that we diagnose any
1564 // further errors in the declaration itself.
1565 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1566 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1567 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1568 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001569 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001570 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001571 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001572 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001573 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001574 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1575 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001576 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001577 }
1578 }
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001580 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1581 assert(Proto && "Function template without prototype?");
1582
1583 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1584 Proto->getNoReturnAttr()) {
1585 // The function has an exception specification or a "noreturn"
1586 // attribute. Substitute into each of the exception types.
1587 llvm::SmallVector<QualType, 4> Exceptions;
1588 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1589 // FIXME: Poor location information!
1590 QualType T
1591 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1592 New->getLocation(), New->getDeclName());
1593 if (T.isNull() ||
1594 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1595 continue;
1596
1597 Exceptions.push_back(T);
1598 }
1599
1600 // Rebuild the function type
1601
1602 const FunctionProtoType *NewProto
1603 = New->getType()->getAs<FunctionProtoType>();
1604 assert(NewProto && "Template instantiation without function prototype?");
1605 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1606 NewProto->arg_type_begin(),
1607 NewProto->getNumArgs(),
1608 NewProto->isVariadic(),
1609 NewProto->getTypeQuals(),
1610 Proto->hasExceptionSpec(),
1611 Proto->hasAnyExceptionSpec(),
1612 Exceptions.size(),
1613 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001614 Proto->getNoReturnAttr(),
1615 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001616 }
1617
Douglas Gregore53060f2009-06-25 22:08:12 +00001618 return false;
1619}
1620
Douglas Gregor5545e162009-03-24 00:38:23 +00001621/// \brief Initializes common fields of an instantiated method
1622/// declaration (New) from the corresponding fields of its template
1623/// (Tmpl).
1624///
1625/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001626bool
1627TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001628 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001629 if (InitFunctionInstantiation(New, Tmpl))
1630 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Douglas Gregor5545e162009-03-24 00:38:23 +00001632 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1633 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001634 if (Tmpl->isVirtualAsWritten())
1635 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001636
1637 // FIXME: attributes
1638 // FIXME: New needs a pointer to Tmpl
1639 return false;
1640}
Douglas Gregora58861f2009-05-13 20:28:22 +00001641
1642/// \brief Instantiate the definition of the given function from its
1643/// template.
1644///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001645/// \param PointOfInstantiation the point at which the instantiation was
1646/// required. Note that this is not precisely a "point of instantiation"
1647/// for the function, but it's close.
1648///
Douglas Gregora58861f2009-05-13 20:28:22 +00001649/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001650/// function template specialization or member function of a class template
1651/// specialization.
1652///
1653/// \param Recursive if true, recursively instantiates any functions that
1654/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001655///
1656/// \param DefinitionRequired if true, then we are performing an explicit
1657/// instantiation where the body of the function is required. Complain if
1658/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001659void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001660 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001661 bool Recursive,
1662 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001663 if (Function->isInvalidDecl())
1664 return;
1665
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001666 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001668 // Never instantiate an explicit specialization.
1669 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1670 return;
1671
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001672 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001673 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001674 Stmt *Pattern = 0;
1675 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001676 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001677
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001678 if (!Pattern) {
1679 if (DefinitionRequired) {
1680 if (Function->getPrimaryTemplate())
1681 Diag(PointOfInstantiation,
1682 diag::err_explicit_instantiation_undefined_func_template)
1683 << Function->getPrimaryTemplate();
1684 else
1685 Diag(PointOfInstantiation,
1686 diag::err_explicit_instantiation_undefined_member)
1687 << 1 << Function->getDeclName() << Function->getDeclContext();
1688
1689 if (PatternDecl)
1690 Diag(PatternDecl->getLocation(),
1691 diag::note_explicit_instantiation_here);
1692 }
1693
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001694 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001695 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001696
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001697 // C++0x [temp.explicit]p9:
1698 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001699 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001700 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001701 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001702 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001703 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001704 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001706 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1707 if (Inst)
1708 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001709
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001710 // If we're performing recursive template instantiation, create our own
1711 // queue of pending implicit instantiations that we will instantiate later,
1712 // while we're still within our own instantiation context.
1713 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1714 if (Recursive)
1715 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001717 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1718
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001719 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001720 // recorded, unless we're actually a member function within a local
1721 // class, in which case we need to merge our results with the parent
1722 // scope (of the enclosing function).
1723 bool MergeWithParentScope = false;
1724 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1725 MergeWithParentScope = Rec->isLocalClass();
1726
1727 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001729 // Introduce the instantiated function parameters into the local
1730 // instantiation scope.
1731 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1732 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1733 Function->getParamDecl(I));
1734
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001735 // Enter the scope of this instantiation. We don't use
1736 // PushDeclContext because we don't have a scope.
1737 DeclContext *PreviousContext = CurContext;
1738 CurContext = Function;
1739
Mike Stump1eb44332009-09-09 15:08:12 +00001740 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001741 getTemplateInstantiationArgs(Function);
1742
1743 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001744 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001745 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1746 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1747 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001748 }
1749
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001750 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001751 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001752
Douglas Gregor52604ab2009-09-11 21:19:12 +00001753 if (Body.isInvalid())
1754 Function->setInvalidDecl();
1755
Mike Stump1eb44332009-09-09 15:08:12 +00001756 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001757 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001758
1759 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001760
1761 DeclGroupRef DG(Function);
1762 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Douglas Gregor60406be2010-01-16 22:29:39 +00001764 // This class may have local implicit instantiations that need to be
1765 // instantiation within this scope.
1766 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1767 Scope.Exit();
1768
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001769 if (Recursive) {
1770 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001771 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001772 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001774 // Restore the set of pending implicit instantiations.
1775 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1776 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001777}
1778
1779/// \brief Instantiate the definition of the given variable from its
1780/// template.
1781///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001782/// \param PointOfInstantiation the point at which the instantiation was
1783/// required. Note that this is not precisely a "point of instantiation"
1784/// for the function, but it's close.
1785///
1786/// \param Var the already-instantiated declaration of a static member
1787/// variable of a class template specialization.
1788///
1789/// \param Recursive if true, recursively instantiates any functions that
1790/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001791///
1792/// \param DefinitionRequired if true, then we are performing an explicit
1793/// instantiation where an out-of-line definition of the member variable
1794/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001795void Sema::InstantiateStaticDataMemberDefinition(
1796 SourceLocation PointOfInstantiation,
1797 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001798 bool Recursive,
1799 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001800 if (Var->isInvalidDecl())
1801 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregor7caa6822009-07-24 20:34:43 +00001803 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001804 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001805 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001806 assert(Def->isStaticDataMember() && "Not a static data member?");
1807 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Douglas Gregor0d035142009-10-27 18:42:08 +00001809 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001810 // We did not find an out-of-line definition of this static data member,
1811 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001812 // instantiate this definition (or provide a specialization for it) in
1813 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001814 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001815 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001816 Diag(PointOfInstantiation,
1817 diag::err_explicit_instantiation_undefined_member)
1818 << 2 << Var->getDeclName() << Var->getDeclContext();
1819 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1820 }
1821
Douglas Gregor7caa6822009-07-24 20:34:43 +00001822 return;
1823 }
1824
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001825 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001826 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001827 return;
1828
1829 // C++0x [temp.explicit]p9:
1830 // Except for inline functions, other explicit instantiation declarations
1831 // have the effect of suppressing the implicit instantiation of the entity
1832 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001833 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001834 == TSK_ExplicitInstantiationDeclaration)
1835 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Douglas Gregor7caa6822009-07-24 20:34:43 +00001837 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1838 if (Inst)
1839 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregor7caa6822009-07-24 20:34:43 +00001841 // If we're performing recursive template instantiation, create our own
1842 // queue of pending implicit instantiations that we will instantiate later,
1843 // while we're still within our own instantiation context.
1844 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1845 if (Recursive)
1846 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Douglas Gregor7caa6822009-07-24 20:34:43 +00001848 // Enter the scope of this instantiation. We don't use
1849 // PushDeclContext because we don't have a scope.
1850 DeclContext *PreviousContext = CurContext;
1851 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001853 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001854 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001855 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001856 CurContext = PreviousContext;
1857
1858 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00001859 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1860 assert(MSInfo && "Missing member specialization information?");
1861 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1862 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001863 DeclGroupRef DG(Var);
1864 Consumer.HandleTopLevelDecl(DG);
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor7caa6822009-07-24 20:34:43 +00001867 if (Recursive) {
1868 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001870 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor7caa6822009-07-24 20:34:43 +00001872 // Restore the set of pending implicit instantiations.
1873 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001874 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001875}
Douglas Gregor815215d2009-05-27 05:35:12 +00001876
Anders Carlsson09025312009-08-29 05:16:22 +00001877void
1878Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1879 const CXXConstructorDecl *Tmpl,
1880 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Anders Carlsson09025312009-08-29 05:16:22 +00001882 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001883 bool AnyErrors = false;
1884
Anders Carlsson09025312009-08-29 05:16:22 +00001885 // Instantiate all the initializers.
1886 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001887 InitsEnd = Tmpl->init_end();
1888 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001889 CXXBaseOrMemberInitializer *Init = *Inits;
1890
1891 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001892 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Anders Carlsson09025312009-08-29 05:16:22 +00001894 // Instantiate all the arguments.
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001895 Expr *InitE = Init->getInit();
1896 if (!InitE) {
1897 // Nothing to instantiate;
1898 } else if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(InitE)) {
1899 if (InstantiateInitializationArguments(*this, ParenList->getExprs(),
1900 ParenList->getNumExprs(),
1901 TemplateArgs, CommaLocs,
1902 NewArgs)) {
1903 AnyErrors = true;
1904 continue;
1905 }
1906 } else {
1907 OwningExprResult InitArg = SubstExpr(InitE, TemplateArgs);
1908 if (InitArg.isInvalid()) {
1909 AnyErrors = true;
1910 continue;
1911 }
1912
1913 NewArgs.push_back(InitArg.release());
Anders Carlsson09025312009-08-29 05:16:22 +00001914 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001915
Anders Carlsson09025312009-08-29 05:16:22 +00001916 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001917 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001918 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001919 TemplateArgs,
1920 Init->getSourceLocation(),
1921 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001922 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001923 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001924 New->setInvalidDecl();
1925 continue;
1926 }
1927
John McCalla93c9342009-12-07 02:54:59 +00001928 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001929 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001930 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001931 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001932 Init->getRParenLoc(),
1933 New->getParent());
1934 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001935 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001937 // Is this an anonymous union?
1938 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001939 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1940 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001941 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001942 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1943 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00001944 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001945
1946 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001947 NewArgs.size(),
1948 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001949 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001950 Init->getRParenLoc());
1951 }
1952
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001953 if (NewInit.isInvalid()) {
1954 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00001955 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001956 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00001957 // FIXME: It would be nice if ASTOwningVector had a release function.
1958 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Anders Carlsson09025312009-08-29 05:16:22 +00001960 NewInits.push_back((MemInitTy *)NewInit.get());
1961 }
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Anders Carlsson09025312009-08-29 05:16:22 +00001964 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001965 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001966 /*FIXME: ColonLoc */
1967 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001968 NewInits.data(), NewInits.size(),
1969 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00001970}
1971
John McCall52a575a2009-08-29 08:11:13 +00001972// TODO: this could be templated if the various decl types used the
1973// same method name.
1974static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1975 ClassTemplateDecl *Instance) {
1976 Pattern = Pattern->getCanonicalDecl();
1977
1978 do {
1979 Instance = Instance->getCanonicalDecl();
1980 if (Pattern == Instance) return true;
1981 Instance = Instance->getInstantiatedFromMemberTemplate();
1982 } while (Instance);
1983
1984 return false;
1985}
1986
Douglas Gregor0d696532009-09-28 06:34:35 +00001987static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1988 FunctionTemplateDecl *Instance) {
1989 Pattern = Pattern->getCanonicalDecl();
1990
1991 do {
1992 Instance = Instance->getCanonicalDecl();
1993 if (Pattern == Instance) return true;
1994 Instance = Instance->getInstantiatedFromMemberTemplate();
1995 } while (Instance);
1996
1997 return false;
1998}
1999
Douglas Gregored9c0f92009-10-29 00:04:11 +00002000static bool
2001isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2002 ClassTemplatePartialSpecializationDecl *Instance) {
2003 Pattern
2004 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2005 do {
2006 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2007 Instance->getCanonicalDecl());
2008 if (Pattern == Instance)
2009 return true;
2010 Instance = Instance->getInstantiatedFromMember();
2011 } while (Instance);
2012
2013 return false;
2014}
2015
John McCall52a575a2009-08-29 08:11:13 +00002016static bool isInstantiationOf(CXXRecordDecl *Pattern,
2017 CXXRecordDecl *Instance) {
2018 Pattern = Pattern->getCanonicalDecl();
2019
2020 do {
2021 Instance = Instance->getCanonicalDecl();
2022 if (Pattern == Instance) return true;
2023 Instance = Instance->getInstantiatedFromMemberClass();
2024 } while (Instance);
2025
2026 return false;
2027}
2028
2029static bool isInstantiationOf(FunctionDecl *Pattern,
2030 FunctionDecl *Instance) {
2031 Pattern = Pattern->getCanonicalDecl();
2032
2033 do {
2034 Instance = Instance->getCanonicalDecl();
2035 if (Pattern == Instance) return true;
2036 Instance = Instance->getInstantiatedFromMemberFunction();
2037 } while (Instance);
2038
2039 return false;
2040}
2041
2042static bool isInstantiationOf(EnumDecl *Pattern,
2043 EnumDecl *Instance) {
2044 Pattern = Pattern->getCanonicalDecl();
2045
2046 do {
2047 Instance = Instance->getCanonicalDecl();
2048 if (Pattern == Instance) return true;
2049 Instance = Instance->getInstantiatedFromMemberEnum();
2050 } while (Instance);
2051
2052 return false;
2053}
2054
John McCalled976492009-12-04 22:46:56 +00002055static bool isInstantiationOf(UsingShadowDecl *Pattern,
2056 UsingShadowDecl *Instance,
2057 ASTContext &C) {
2058 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2059}
2060
2061static bool isInstantiationOf(UsingDecl *Pattern,
2062 UsingDecl *Instance,
2063 ASTContext &C) {
2064 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2065}
2066
John McCall7ba107a2009-11-18 02:36:19 +00002067static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2068 UsingDecl *Instance,
2069 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002070 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002071}
2072
2073static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002074 UsingDecl *Instance,
2075 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002076 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002077}
2078
John McCall52a575a2009-08-29 08:11:13 +00002079static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2080 VarDecl *Instance) {
2081 assert(Instance->isStaticDataMember());
2082
2083 Pattern = Pattern->getCanonicalDecl();
2084
2085 do {
2086 Instance = Instance->getCanonicalDecl();
2087 if (Pattern == Instance) return true;
2088 Instance = Instance->getInstantiatedFromStaticDataMember();
2089 } while (Instance);
2090
2091 return false;
2092}
2093
John McCalled976492009-12-04 22:46:56 +00002094// Other is the prospective instantiation
2095// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002096static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002097 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002098 if (UnresolvedUsingTypenameDecl *UUD
2099 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2100 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2101 return isInstantiationOf(UUD, UD, Ctx);
2102 }
2103 }
2104
2105 if (UnresolvedUsingValueDecl *UUD
2106 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002107 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2108 return isInstantiationOf(UUD, UD, Ctx);
2109 }
2110 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002111
Anders Carlsson0d8df782009-08-29 19:37:28 +00002112 return false;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
John McCall52a575a2009-08-29 08:11:13 +00002115 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2116 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002117
John McCall52a575a2009-08-29 08:11:13 +00002118 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2119 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002120
John McCall52a575a2009-08-29 08:11:13 +00002121 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2122 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002123
Douglas Gregor7caa6822009-07-24 20:34:43 +00002124 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002125 if (Var->isStaticDataMember())
2126 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2127
2128 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2129 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002130
Douglas Gregor0d696532009-09-28 06:34:35 +00002131 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2132 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2133
Douglas Gregored9c0f92009-10-29 00:04:11 +00002134 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2135 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2136 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2137 PartialSpec);
2138
Anders Carlssond8b285f2009-09-01 04:26:58 +00002139 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2140 if (!Field->getDeclName()) {
2141 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002142 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002143 cast<FieldDecl>(D);
2144 }
2145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146
John McCalled976492009-12-04 22:46:56 +00002147 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2148 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2149
2150 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2151 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2152
Douglas Gregor815215d2009-05-27 05:35:12 +00002153 return D->getDeclName() && isa<NamedDecl>(Other) &&
2154 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2155}
2156
2157template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002158static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002159 NamedDecl *D,
2160 ForwardIterator first,
2161 ForwardIterator last) {
2162 for (; first != last; ++first)
2163 if (isInstantiationOf(Ctx, D, *first))
2164 return cast<NamedDecl>(*first);
2165
2166 return 0;
2167}
2168
John McCall02cace72009-08-28 07:59:38 +00002169/// \brief Finds the instantiation of the given declaration context
2170/// within the current instantiation.
2171///
2172/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002173DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002174 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002175 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002176 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002177 return cast_or_null<DeclContext>(ID);
2178 } else return DC;
2179}
2180
Douglas Gregored961e72009-05-27 17:54:46 +00002181/// \brief Find the instantiation of the given declaration within the
2182/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002183///
2184/// This routine is intended to be used when \p D is a declaration
2185/// referenced from within a template, that needs to mapped into the
2186/// corresponding declaration within an instantiation. For example,
2187/// given:
2188///
2189/// \code
2190/// template<typename T>
2191/// struct X {
2192/// enum Kind {
2193/// KnownValue = sizeof(T)
2194/// };
2195///
2196/// bool getKind() const { return KnownValue; }
2197/// };
2198///
2199/// template struct X<int>;
2200/// \endcode
2201///
2202/// In the instantiation of X<int>::getKind(), we need to map the
2203/// EnumConstantDecl for KnownValue (which refers to
2204/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002205/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2206/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002207NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002208 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002209 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002210 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002211 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002212 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002213 // D is a local of some kind. Look into the map of local
2214 // declarations to their instantiations.
2215 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2216 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002217
Douglas Gregore95b4092009-09-16 18:34:49 +00002218 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2219 if (!Record->isDependentContext())
2220 return D;
2221
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002222 // If the RecordDecl is actually the injected-class-name or a
2223 // "templated" declaration for a class template, class template
2224 // partial specialization, or a member class of a class template,
2225 // substitute into the injected-class-name of the class template
2226 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002227 QualType T;
2228 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2229
2230 if (ClassTemplate) {
2231 T = ClassTemplate->getInjectedClassNameType(Context);
2232 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2233 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2234 T = Context.getTypeDeclType(Record);
2235 ClassTemplate = PartialSpec->getSpecializedTemplate();
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002236 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002237
2238 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002239 // Substitute into the injected-class-name to get the type
2240 // corresponding to the instantiation we want, which may also be
2241 // the current instantiation (if we're in a template
2242 // definition). This substitution should never fail, since we
2243 // know we can instantiate the injected-class-name or we
2244 // wouldn't have gotten to the injected-class-name!
2245
2246 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2247 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002248 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2249 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2250
2251 if (!T->isDependentType()) {
2252 assert(T->isRecordType() && "Instantiation must produce a record type");
2253 return T->getAs<RecordType>()->getDecl();
2254 }
2255
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002256 // We are performing "partial" template instantiation to create
2257 // the member declarations for the members of a class template
2258 // specialization. Therefore, D is actually referring to something
2259 // in the current instantiation. Look through the current
2260 // context, which contains actual instantiations, to find the
2261 // instantiation of the "current instantiation" that D refers
2262 // to.
2263 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002264 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002265 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002266 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002267 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002268 if (isInstantiationOf(ClassTemplate,
2269 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002270 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002271
2272 if (!DC->isDependentContext())
2273 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002274 }
2275
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002276 // We're performing "instantiation" of a member of the current
2277 // instantiation while we are type-checking the
2278 // definition. Compute the declaration context and return that.
2279 assert(!SawNonDependentContext &&
2280 "No dependent context while instantiating record");
2281 DeclContext *DC = computeDeclContext(T);
2282 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002283 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002284 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002285 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002286
Douglas Gregore95b4092009-09-16 18:34:49 +00002287 // Fall through to deal with other dependent record types (e.g.,
2288 // anonymous unions in class templates).
2289 }
John McCall52a575a2009-08-29 08:11:13 +00002290
Douglas Gregore95b4092009-09-16 18:34:49 +00002291 if (!ParentDC->isDependentContext())
2292 return D;
2293
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002294 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002295 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002296 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregor815215d2009-05-27 05:35:12 +00002298 if (ParentDC != D->getDeclContext()) {
2299 // We performed some kind of instantiation in the parent context,
2300 // so now we need to look into the instantiated parent context to
2301 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002302
2303 // If our context is a class template specialization, we may need
2304 // to instantiate it before performing lookup into that context.
2305 if (ClassTemplateSpecializationDecl *Spec
2306 = dyn_cast<ClassTemplateSpecializationDecl>(ParentDC)) {
2307 if (!Spec->isDependentContext()) {
2308 QualType T = Context.getTypeDeclType(Spec);
2309 if (const TagType *Tag = T->getAs<TagType>())
2310 if (!Tag->isBeingDefined() &&
2311 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2312 return 0;
2313 }
2314 }
2315
Douglas Gregor815215d2009-05-27 05:35:12 +00002316 NamedDecl *Result = 0;
2317 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002318 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002319 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2320 } else {
2321 // Since we don't have a name for the entity we're looking for,
2322 // our only option is to walk through all of the declarations to
2323 // find that name. This will occur in a few cases:
2324 //
2325 // - anonymous struct/union within a template
2326 // - unnamed class/struct/union/enum within a template
2327 //
2328 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002329 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002330 ParentDC->decls_begin(),
2331 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
John McCall9f54ad42009-12-10 09:41:52 +00002334 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002335 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2336 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002337 && "Unable to find instantiation of declaration!");
2338
Douglas Gregor815215d2009-05-27 05:35:12 +00002339 D = Result;
2340 }
2341
Douglas Gregor815215d2009-05-27 05:35:12 +00002342 return D;
2343}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002344
Mike Stump1eb44332009-09-09 15:08:12 +00002345/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002346/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002347void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2348 while (!PendingLocalImplicitInstantiations.empty() ||
2349 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2350 PendingImplicitInstantiation Inst;
2351
2352 if (PendingLocalImplicitInstantiations.empty()) {
2353 Inst = PendingImplicitInstantiations.front();
2354 PendingImplicitInstantiations.pop_front();
2355 } else {
2356 Inst = PendingLocalImplicitInstantiations.front();
2357 PendingLocalImplicitInstantiations.pop_front();
2358 }
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Douglas Gregor7caa6822009-07-24 20:34:43 +00002360 // Instantiate function definitions
2361 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002362 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002363 Function->getLocation(), *this,
2364 Context.getSourceManager(),
2365 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002367 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002368 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002369 continue;
2370 }
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Douglas Gregor7caa6822009-07-24 20:34:43 +00002372 // Instantiate static data member definitions.
2373 VarDecl *Var = cast<VarDecl>(Inst.first);
2374 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002375
Chandler Carruth291b4412010-02-13 10:17:50 +00002376 // Don't try to instantiate declarations if the most recent redeclaration
2377 // is invalid.
2378 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2379 continue;
2380
2381 // Check if the most recent declaration has changed the specialization kind
2382 // and removed the need for implicit instantiation.
2383 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2384 case TSK_Undeclared:
2385 assert(false && "Cannot instantitiate an undeclared specialization.");
2386 case TSK_ExplicitInstantiationDeclaration:
2387 case TSK_ExplicitInstantiationDefinition:
2388 case TSK_ExplicitSpecialization:
2389 continue; // No longer need implicit instantiation.
2390 case TSK_ImplicitInstantiation:
2391 break;
2392 }
2393
Mike Stump1eb44332009-09-09 15:08:12 +00002394 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002395 Var->getLocation(), *this,
2396 Context.getSourceManager(),
2397 "instantiating static data member "
2398 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Douglas Gregor7caa6822009-07-24 20:34:43 +00002400 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002401 }
2402}