blob: e6be5389cd06c6a178e3ed2cb023310613c5e727 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000020#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000022
23using namespace clang;
24
25namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000026 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000070 Decl *VisitUsingDecl(UsingDecl *D);
71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000072 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor8dbc2692009-03-17 21:15:40 +000075 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000076 Decl *VisitDecl(Decl *D) {
77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78 Diagnostic::Error,
79 "cannot instantiate %0 yet");
80 SemaRef.Diag(D->getLocation(), DiagID)
81 << D->getDeclKindName();
82
Douglas Gregor8dbc2692009-03-17 21:15:40 +000083 return 0;
84 }
Douglas Gregor5545e162009-03-24 00:38:23 +000085
John McCallfd810b12009-08-14 02:03:10 +000086 const LangOptions &getLangOptions() {
87 return SemaRef.getLangOptions();
88 }
89
Douglas Gregor5545e162009-03-24 00:38:23 +000090 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000091 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000092 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000093 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000094 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000095
96 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000097 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000098
99 bool InstantiateClassTemplatePartialSpecialization(
100 ClassTemplateDecl *ClassTemplate,
101 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 };
103}
104
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000105// FIXME: Is this too simple?
106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
107 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
108 TmplAttr = TmplAttr->getNext()) {
109
110 // FIXME: Is cloning correct for all attributes?
111 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
112
113 New->addAttr(NewAttr);
114 }
115}
116
Douglas Gregor4f722be2009-03-25 15:45:12 +0000117Decl *
118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
119 assert(false && "Translation units cannot be instantiated");
120 return D;
121}
122
123Decl *
124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125 assert(false && "Namespaces cannot be instantiated");
126 return D;
127}
128
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
130 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000131 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000132 if (DI->getType()->isDependentType()) {
133 DI = SemaRef.SubstType(DI, TemplateArgs,
134 D->getLocation(), D->getDeclName());
135 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000137 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 }
139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000141 // Create the new typedef
142 TypedefDecl *Typedef
143 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000144 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 if (Invalid)
146 Typedef->setInvalidDecl();
147
John McCall5126fd02009-12-30 00:31:22 +0000148 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
149 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Prev, TemplateArgs);
150 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
151 }
152
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000153 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000155 return Typedef;
156}
157
Douglas Gregor6eef5192009-12-14 19:27:10 +0000158/// \brief Instantiate the arguments provided as part of initialization.
159///
160/// \returns true if an error occurred, false otherwise.
161static bool InstantiateInitializationArguments(Sema &SemaRef,
162 Expr **Args, unsigned NumArgs,
163 const MultiLevelTemplateArgumentList &TemplateArgs,
164 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
165 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
166 for (unsigned I = 0; I != NumArgs; ++I) {
167 // When we hit the first defaulted argument, break out of the loop:
168 // we don't pass those default arguments on.
169 if (Args[I]->isDefaultArgument())
170 break;
171
172 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
173 if (Arg.isInvalid())
174 return true;
175
176 Expr *ArgExpr = (Expr *)Arg.get();
177 InitArgs.push_back(Arg.release());
178
179 // FIXME: We're faking all of the comma locations. Do we need them?
180 FakeCommaLocs.push_back(
181 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
182 }
183
184 return false;
185}
186
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000187Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000188 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000189 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000190 TemplateArgs,
191 D->getTypeSpecStartLoc(),
192 D->getDeclName());
193 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000194 return 0;
195
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000196 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000197 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
198 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000199 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000200 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000201 Var->setThreadSpecified(D->isThreadSpecified());
202 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
203 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000204
205 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000206 // out-of-line, the instantiation will have the same lexical
207 // context (which will be a namespace scope) as the template.
208 if (D->isOutOfLine())
209 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Mike Stump390b4cc2009-05-16 07:39:55 +0000211 // FIXME: In theory, we could have a previous declaration for variables that
212 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000213 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000214 // FIXME: having to fake up a LookupResult is dumb.
215 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
216 Sema::LookupOrdinaryName);
217 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Douglas Gregor7caa6822009-07-24 20:34:43 +0000219 if (D->isOutOfLine()) {
220 D->getLexicalDeclContext()->addDecl(Var);
221 Owner->makeDeclVisibleInContext(Var);
222 } else {
223 Owner->addDecl(Var);
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000226 // Link instantiations of static data members back to the template from
227 // which they were instantiated.
228 if (Var->isStaticDataMember())
229 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000230 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000231
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000232 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000233 if (Var->isStaticDataMember() && !D->isOutOfLine())
234 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
235 else
236 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
237
Douglas Gregor6eef5192009-12-14 19:27:10 +0000238 // Extract the initializer, skipping through any temporary-binding
239 // expressions and look at the subexpression as it was written.
240 Expr *DInit = D->getInit();
241 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
242 DInit = Binder->getSubExpr();
243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
244 DInit = ICE->getSubExprAsWritten();
245
246 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
247 // The initializer is a parenthesized list of expressions that is
248 // type-dependent. Instantiate each of the expressions; we'll be
249 // performing direct initialization with them.
250 llvm::SmallVector<SourceLocation, 4> CommaLocs;
251 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
252 if (!InstantiateInitializationArguments(SemaRef,
253 PLE->getExprs(),
254 PLE->getNumExprs(),
255 TemplateArgs,
256 CommaLocs, InitArgs)) {
257 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000258 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000259 PLE->getLParenLoc(),
260 move_arg(InitArgs),
261 CommaLocs.data(),
262 PLE->getRParenLoc());
263 }
264 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
265 // The initializer resolved to a constructor. Instantiate the constructor
266 // arguments.
267 llvm::SmallVector<SourceLocation, 4> CommaLocs;
268 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
269
270 if (!InstantiateInitializationArguments(SemaRef,
271 Construct->getArgs(),
272 Construct->getNumArgs(),
273 TemplateArgs,
274 CommaLocs, InitArgs)) {
275 if (D->hasCXXDirectInitializer()) {
276 SourceLocation FakeLParenLoc =
277 SemaRef.PP.getLocForEndOfToken(D->getLocation());
278 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
279 : CommaLocs.back();
280 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
281 FakeLParenLoc,
282 move_arg(InitArgs),
283 CommaLocs.data(),
284 FakeRParenLoc);
285 } else if (InitArgs.size() == 1) {
286 Expr *Init = (Expr*)(InitArgs.take()[0]);
287 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
288 SemaRef.Owned(Init),
289 false);
290 } else {
291 assert(InitArgs.size() == 0);
292 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
293 }
294 }
295 } else {
296 OwningExprResult Init
297 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
298
299 // FIXME: Not happy about invalidating decls just because of a bad
300 // initializer, unless it affects the type.
301 if (Init.isInvalid())
302 Var->setInvalidDecl();
303 else
304 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
305 D->hasCXXDirectInitializer());
306 }
307
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000308 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000309 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
310 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000311
312 return Var;
313}
314
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000315Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
316 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000317 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000318 if (DI->getType()->isDependentType()) {
319 DI = SemaRef.SubstType(DI, TemplateArgs,
320 D->getLocation(), D->getDeclName());
321 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000322 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000323 Invalid = true;
324 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000325 // C++ [temp.arg.type]p3:
326 // If a declaration acquires a function type through a type
327 // dependent on a template-parameter and this causes a
328 // declaration that does not use the syntactic form of a
329 // function declarator to have function type, the program is
330 // ill-formed.
331 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000332 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000333 Invalid = true;
334 }
335 }
336
337 Expr *BitWidth = D->getBitWidth();
338 if (Invalid)
339 BitWidth = 0;
340 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000341 // The bit-width expression is not potentially evaluated.
342 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000344 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000345 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000346 if (InstantiatedBitWidth.isInvalid()) {
347 Invalid = true;
348 BitWidth = 0;
349 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000350 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351 }
352
John McCall07fb6be2009-10-22 23:33:21 +0000353 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
354 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000355 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000356 D->getLocation(),
357 D->isMutable(),
358 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000359 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000360 D->getAccess(),
361 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000362 if (!Field) {
363 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000364 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000367 InstantiateAttrs(D, Field);
368
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000369 if (Invalid)
370 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 if (!Field->getDeclName()) {
373 // Keep track of where this decl came from.
374 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000377 Field->setImplicit(D->isImplicit());
378 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000379
380 return Field;
381}
382
John McCall02cace72009-08-28 07:59:38 +0000383Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
384 FriendDecl::FriendUnion FU;
385
386 // Handle friend type expressions by simply substituting template
387 // parameters into the pattern type.
388 if (Type *Ty = D->getFriendType()) {
389 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
390 D->getLocation(), DeclarationName());
391 if (T.isNull()) return 0;
392
393 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
394 FU = T.getTypePtr();
395
396 // Handle everything else by appropriate substitution.
397 } else {
398 NamedDecl *ND = D->getFriendDecl();
399 assert(ND && "friend decl must be a decl or a type!");
400
Douglas Gregora735b202009-10-13 14:39:41 +0000401 // FIXME: We have a problem here, because the nested call to Visit(ND)
402 // will inject the thing that the friend references into the current
403 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000404 Decl *NewND;
405
406 // Hack to make this work almost well pending a rewrite.
407 if (ND->getDeclContext()->isRecord())
408 NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs);
Douglas Gregor7557a132009-12-24 20:56:24 +0000409 else if (D->wasSpecialization()) {
410 // Totally egregious hack to work around PR5866
411 return 0;
412 } else
John McCalle129d442009-12-17 23:21:11 +0000413 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000414 if (!NewND) return 0;
415
416 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
John McCall02cace72009-08-28 07:59:38 +0000419 FriendDecl *FD =
420 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
421 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000422 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000423 Owner->addDecl(FD);
424 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000425}
426
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
428 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregorac7610d2009-06-22 20:57:11 +0000430 // The expression in a static assertion is not potentially evaluated.
431 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000433 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000434 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000435 if (InstantiatedAssertExpr.isInvalid())
436 return 0;
437
Douglas Gregor43d9d922009-08-08 01:41:12 +0000438 OwningExprResult Message(SemaRef, D->getMessage());
439 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000440 Decl *StaticAssert
441 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000442 move(InstantiatedAssertExpr),
443 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444 return StaticAssert;
445}
446
447Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000448 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000449 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000450 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000451 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000452 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000453 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000454 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455 Enum->startDefinition();
456
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000457 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000458
459 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000460 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
461 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000462 EC != ECEnd; ++EC) {
463 // The specified value for the enumerator.
464 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000465 if (Expr *UninstValue = EC->getInitExpr()) {
466 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000467 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000468 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
John McCallce3ff2b2009-08-25 22:02:44 +0000470 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000471 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472
473 // Drop the initial value and continue.
474 bool isInvalid = false;
475 if (Value.isInvalid()) {
476 Value = SemaRef.Owned((Expr *)0);
477 isInvalid = true;
478 }
479
Mike Stump1eb44332009-09-09 15:08:12 +0000480 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
482 EC->getLocation(), EC->getIdentifier(),
483 move(Value));
484
485 if (isInvalid) {
486 if (EnumConst)
487 EnumConst->setInvalidDecl();
488 Enum->setInvalidDecl();
489 }
490
491 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000492 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000493 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000494 LastEnumConst = EnumConst;
495 }
496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000498 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000499 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000500 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
501 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000502 &Enumerators[0], Enumerators.size(),
503 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000504
505 return Enum;
506}
507
Douglas Gregor6477b692009-03-25 15:04:13 +0000508Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
509 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
510 return 0;
511}
512
Douglas Gregored9c0f92009-10-29 00:04:11 +0000513namespace {
514 class SortDeclByLocation {
515 SourceManager &SourceMgr;
516
517 public:
518 explicit SortDeclByLocation(SourceManager &SourceMgr)
519 : SourceMgr(SourceMgr) { }
520
521 bool operator()(const Decl *X, const Decl *Y) const {
522 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
523 Y->getLocation());
524 }
525 };
526}
527
John McCalle29ba202009-08-20 01:44:21 +0000528Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000529 // Create a local instantiation scope for this class template, which
530 // will contain the instantiations of the template parameters.
531 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000532 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000533 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000534 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000535 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000536
537 CXXRecordDecl *Pattern = D->getTemplatedDecl();
538 CXXRecordDecl *RecordInst
539 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
540 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000541 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
542 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000543
544 ClassTemplateDecl *Inst
545 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
546 D->getIdentifier(), InstParams, RecordInst, 0);
547 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000548 if (D->getFriendObjectKind())
549 Inst->setObjectOfFriendDecl(true);
550 else
551 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000552 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000553
554 // Trigger creation of the type for the instantiation.
555 SemaRef.Context.getTypeDeclType(RecordInst);
556
Douglas Gregor259571e2009-10-30 22:42:42 +0000557 // Finish handling of friends.
558 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000559 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000560 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000561
John McCalle29ba202009-08-20 01:44:21 +0000562 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000563
564 // First, we sort the partial specializations by location, so
565 // that we instantiate them in the order they were declared.
566 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
567 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
568 P = D->getPartialSpecializations().begin(),
569 PEnd = D->getPartialSpecializations().end();
570 P != PEnd; ++P)
571 PartialSpecs.push_back(&*P);
572 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
573 SortDeclByLocation(SemaRef.SourceMgr));
574
575 // Instantiate all of the partial specializations of this member class
576 // template.
577 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
578 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
579
John McCalle29ba202009-08-20 01:44:21 +0000580 return Inst;
581}
582
Douglas Gregord60e1052009-08-27 16:57:43 +0000583Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000584TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
585 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000586 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
587
588 // Lookup the already-instantiated declaration in the instantiation
589 // of the class template and return that.
590 DeclContext::lookup_result Found
591 = Owner->lookup(ClassTemplate->getDeclName());
592 if (Found.first == Found.second)
593 return 0;
594
595 ClassTemplateDecl *InstClassTemplate
596 = dyn_cast<ClassTemplateDecl>(*Found.first);
597 if (!InstClassTemplate)
598 return 0;
599
600 Decl *DCanon = D->getCanonicalDecl();
601 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
602 P = InstClassTemplate->getPartialSpecializations().begin(),
603 PEnd = InstClassTemplate->getPartialSpecializations().end();
604 P != PEnd; ++P) {
605 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
606 return &*P;
607 }
608
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000609 return 0;
610}
611
612Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000613TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000614 // Create a local instantiation scope for this function template, which
615 // will contain the instantiations of the template parameters and then get
616 // merged with the local instantiation scope for the function template
617 // itself.
618 Sema::LocalInstantiationScope Scope(SemaRef);
619
Douglas Gregord60e1052009-08-27 16:57:43 +0000620 TemplateParameterList *TempParams = D->getTemplateParameters();
621 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000622 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000623 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000624
Douglas Gregora735b202009-10-13 14:39:41 +0000625 FunctionDecl *Instantiated = 0;
626 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
627 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
628 InstParams));
629 else
630 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
631 D->getTemplatedDecl(),
632 InstParams));
633
634 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000635 return 0;
636
Mike Stump1eb44332009-09-09 15:08:12 +0000637 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000638 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000639 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000640 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000641 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000642 assert(InstTemplate &&
643 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000644
645 // Link the instantiation back to the pattern *unless* this is a
646 // non-definition friend declaration.
647 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
648 !(InstTemplate->getFriendObjectKind() &&
649 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000650 InstTemplate->setInstantiatedFromMemberTemplate(D);
651
652 // Add non-friends into the owner.
653 if (!InstTemplate->getFriendObjectKind())
654 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000655 return InstTemplate;
656}
657
Douglas Gregord475b8d2009-03-25 21:17:03 +0000658Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
659 CXXRecordDecl *PrevDecl = 0;
660 if (D->isInjectedClassName())
661 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000662 else if (D->getPreviousDeclaration()) {
663 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
664 TemplateArgs);
665 if (!Prev) return 0;
666 PrevDecl = cast<CXXRecordDecl>(Prev);
667 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000668
669 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000670 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000671 D->getLocation(), D->getIdentifier(),
672 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000673 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000674 // FIXME: Check against AS_none is an ugly hack to work around the issue that
675 // the tag decls introduced by friend class declarations don't have an access
676 // specifier. Remove once this area of the code gets sorted out.
677 if (D->getAccess() != AS_none)
678 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000679 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000680 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000681
John McCall02cace72009-08-28 07:59:38 +0000682 // If the original function was part of a friend declaration,
683 // inherit its namespace state.
684 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
685 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
686
Anders Carlssond8b285f2009-09-01 04:26:58 +0000687 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
688
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000689 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000690 return Record;
691}
692
John McCall02cace72009-08-28 07:59:38 +0000693/// Normal class members are of more specific types and therefore
694/// don't make it here. This function serves two purposes:
695/// 1) instantiating function templates
696/// 2) substituting friend declarations
697/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000698Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000699 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000700 // Check whether there is already a function template specialization for
701 // this declaration.
702 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
703 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000704 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000705 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000706 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000707 TemplateArgs.getInnermost().getFlatArgumentList(),
708 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000709 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
711 FunctionTemplateSpecializationInfo *Info
712 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000713 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Douglas Gregor127102b2009-06-29 20:59:39 +0000715 // If we already have a function template specialization, return it.
716 if (Info)
717 return Info->Function;
718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Douglas Gregor79c22782010-01-16 20:21:20 +0000720 bool MergeWithParentScope = (TemplateParams != 0) ||
721 !(isa<Decl>(Owner) &&
722 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
723 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregore53060f2009-06-25 22:08:12 +0000725 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000726 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000727 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000728 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000729
Douglas Gregore53060f2009-06-25 22:08:12 +0000730 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000731 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
732 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000733 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000734 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000735 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000736 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000737 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000738 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Douglas Gregore53060f2009-06-25 22:08:12 +0000740 // Attach the parameters
741 for (unsigned P = 0; P < Params.size(); ++P)
742 Params[P]->setOwningFunction(Function);
743 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000744
Douglas Gregora735b202009-10-13 14:39:41 +0000745 if (TemplateParams) {
746 // Our resulting instantiation is actually a function template, since we
747 // are substituting only the outer template parameters. For example, given
748 //
749 // template<typename T>
750 // struct X {
751 // template<typename U> friend void f(T, U);
752 // };
753 //
754 // X<int> x;
755 //
756 // We are instantiating the friend function template "f" within X<int>,
757 // which means substituting int for T, but leaving "f" as a friend function
758 // template.
759 // Build the function template itself.
760 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
761 Function->getLocation(),
762 Function->getDeclName(),
763 TemplateParams, Function);
764 Function->setDescribedFunctionTemplate(FunctionTemplate);
765 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000766 } else if (FunctionTemplate) {
767 // Record this function template specialization.
768 Function->setFunctionTemplateSpecialization(SemaRef.Context,
769 FunctionTemplate,
770 &TemplateArgs.getInnermost(),
771 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000772 }
Douglas Gregora735b202009-10-13 14:39:41 +0000773
Douglas Gregore53060f2009-06-25 22:08:12 +0000774 if (InitFunctionInstantiation(Function, D))
775 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Douglas Gregore53060f2009-06-25 22:08:12 +0000777 bool Redeclaration = false;
778 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000779
John McCall68263142009-11-18 22:49:29 +0000780 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
781 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
782
Douglas Gregora735b202009-10-13 14:39:41 +0000783 if (TemplateParams || !FunctionTemplate) {
784 // Look only into the namespace where the friend would be declared to
785 // find a previous declaration. This is the innermost enclosing namespace,
786 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000787 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000788
Douglas Gregora735b202009-10-13 14:39:41 +0000789 // In C++, the previous declaration we find might be a tag type
790 // (class or enum). In this case, the new declaration will hide the
791 // tag type. Note that this does does not apply if we're declaring a
792 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000793 if (Previous.isSingleTagDecl())
794 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000795 }
796
John McCall9f54ad42009-12-10 09:41:52 +0000797 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
798 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000799 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000800
Douglas Gregora735b202009-10-13 14:39:41 +0000801 // If the original function was part of a friend declaration,
802 // inherit its namespace state and add it to the owner.
803 NamedDecl *FromFriendD
804 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
805 if (FromFriendD->getFriendObjectKind()) {
806 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000807 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000808 if (TemplateParams) {
809 ToFriendD = cast<NamedDecl>(FunctionTemplate);
810 PrevDecl = FunctionTemplate->getPreviousDeclaration();
811 } else {
812 ToFriendD = Function;
813 PrevDecl = Function->getPreviousDeclaration();
814 }
815 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
816 if (!Owner->isDependentContext() && !PrevDecl)
817 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
818
819 if (!TemplateParams)
820 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
821 }
822
Douglas Gregore53060f2009-06-25 22:08:12 +0000823 return Function;
824}
825
Douglas Gregord60e1052009-08-27 16:57:43 +0000826Decl *
827TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
828 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000829 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
830 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000831 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000832 // We are creating a function template specialization from a function
833 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000834 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000835 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000836 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000837 TemplateArgs.getInnermost().getFlatArgumentList(),
838 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000839 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
841 FunctionTemplateSpecializationInfo *Info
842 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000843 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Douglas Gregor6b906862009-08-21 00:16:32 +0000845 // If we already have a function template specialization, return it.
846 if (Info)
847 return Info->Function;
848 }
849
Douglas Gregor79c22782010-01-16 20:21:20 +0000850 bool MergeWithParentScope = (TemplateParams != 0) ||
851 !(isa<Decl>(Owner) &&
852 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
853 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000854
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000855 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000856 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000857 if (T.isNull())
858 return 0;
859
860 // Build the instantiated method declaration.
861 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000862 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregordec06662009-08-21 18:42:58 +0000864 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000865 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000866 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
867 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
868 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000869 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
870 Constructor->getLocation(),
871 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000872 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000873 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000874 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000875 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
876 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
877 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
878 SemaRef.Context.getCanonicalType(ClassTy));
879 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
880 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000881 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000882 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000883 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000884 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000885 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000886 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
887 ConvTy);
888 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
889 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000890 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000891 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000892 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000893 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000895 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000896 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000897 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000898
Douglas Gregord60e1052009-08-27 16:57:43 +0000899 if (TemplateParams) {
900 // Our resulting instantiation is actually a function template, since we
901 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000902 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000903 // template<typename T>
904 // struct X {
905 // template<typename U> void f(T, U);
906 // };
907 //
908 // X<int> x;
909 //
910 // We are instantiating the member template "f" within X<int>, which means
911 // substituting int for T, but leaving "f" as a member function template.
912 // Build the function template itself.
913 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
914 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000915 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000916 TemplateParams, Method);
917 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000918 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000919 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000920 } else if (FunctionTemplate) {
921 // Record this function template specialization.
922 Method->setFunctionTemplateSpecialization(SemaRef.Context,
923 FunctionTemplate,
924 &TemplateArgs.getInnermost(),
925 InsertPos);
926 } else {
927 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000928 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000929 }
930
Mike Stump1eb44332009-09-09 15:08:12 +0000931 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000932 // out-of-line, the instantiation will have the same lexical
933 // context (which will be a namespace scope) as the template.
934 if (D->isOutOfLine())
935 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregor5545e162009-03-24 00:38:23 +0000937 // Attach the parameters
938 for (unsigned P = 0; P < Params.size(); ++P)
939 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000940 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000941
942 if (InitMethodInstantiation(Method, D))
943 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000944
John McCall68263142009-11-18 22:49:29 +0000945 LookupResult Previous(SemaRef, Name, SourceLocation(),
946 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregord60e1052009-08-27 16:57:43 +0000948 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000949 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Douglas Gregordec06662009-08-21 18:42:58 +0000951 // In C++, the previous declaration we find might be a tag type
952 // (class or enum). In this case, the new declaration will hide the
953 // tag type. Note that this does does not apply if we're declaring a
954 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000955 if (Previous.isSingleTagDecl())
956 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000957 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000958
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000959 bool Redeclaration = false;
960 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000961 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000962 /*FIXME:*/OverloadableAttrRequired);
963
Douglas Gregor4ba31362009-12-01 17:24:26 +0000964 if (D->isPure())
965 SemaRef.CheckPureMethod(Method, SourceRange());
966
John McCall68263142009-11-18 22:49:29 +0000967 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000968 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000969 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000971 return Method;
972}
973
Douglas Gregor615c5d42009-03-24 16:43:20 +0000974Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000975 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000976}
977
Douglas Gregor03b2b072009-03-24 00:15:49 +0000978Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000979 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000980}
981
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000982Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000983 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000984}
985
Douglas Gregor6477b692009-03-25 15:04:13 +0000986ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000987 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000988 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000989 if (DI) {
990 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
991 D->getDeclName());
992 if (DI) T = DI->getType();
993 } else {
994 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
995 D->getDeclName());
996 DI = 0;
997 }
998
999 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001000 return 0;
1001
John McCall58e46772009-10-23 21:48:59 +00001002 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001003
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001004 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001005 ParmVarDecl *Param
1006 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1007 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001008
Anders Carlsson9351c172009-08-25 03:18:48 +00001009 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001010 if (D->hasUninstantiatedDefaultArg())
1011 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001012 else if (Expr *Arg = D->getDefaultArg())
1013 Param->setUninstantiatedDefaultArg(Arg);
1014
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001015 // Note: we don't try to instantiate function parameters until after
1016 // we've instantiated the function's type. Therefore, we don't have
1017 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001018 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001019 return Param;
1020}
1021
John McCalle29ba202009-08-20 01:44:21 +00001022Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1023 TemplateTypeParmDecl *D) {
1024 // TODO: don't always clone when decls are refcounted.
1025 const Type* T = D->getTypeForDecl();
1026 assert(T->isTemplateTypeParmType());
1027 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001028
John McCalle29ba202009-08-20 01:44:21 +00001029 TemplateTypeParmDecl *Inst =
1030 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001031 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001032 TTPT->getName(),
1033 D->wasDeclaredWithTypename(),
1034 D->isParameterPack());
1035
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001036 if (D->hasDefaultArgument())
1037 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001038
Douglas Gregor550d9b22009-10-31 17:21:17 +00001039 // Introduce this template parameter's instantiation into the instantiation
1040 // scope.
1041 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1042
John McCalle29ba202009-08-20 01:44:21 +00001043 return Inst;
1044}
1045
Douglas Gregor33642df2009-10-23 23:25:44 +00001046Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1047 NonTypeTemplateParmDecl *D) {
1048 // Substitute into the type of the non-type template parameter.
1049 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001050 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001051 if (DI) {
1052 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1053 D->getDeclName());
1054 if (DI) T = DI->getType();
1055 } else {
1056 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1057 D->getDeclName());
1058 DI = 0;
1059 }
1060 if (T.isNull())
1061 return 0;
1062
1063 // Check that this type is acceptable for a non-type template parameter.
1064 bool Invalid = false;
1065 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1066 if (T.isNull()) {
1067 T = SemaRef.Context.IntTy;
1068 Invalid = true;
1069 }
1070
1071 NonTypeTemplateParmDecl *Param
1072 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1073 D->getDepth() - 1, D->getPosition(),
1074 D->getIdentifier(), T, DI);
1075 if (Invalid)
1076 Param->setInvalidDecl();
1077
1078 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001079
1080 // Introduce this template parameter's instantiation into the instantiation
1081 // scope.
1082 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001083 return Param;
1084}
1085
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001086Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001087TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1088 TemplateTemplateParmDecl *D) {
1089 // Instantiate the template parameter list of the template template parameter.
1090 TemplateParameterList *TempParams = D->getTemplateParameters();
1091 TemplateParameterList *InstParams;
1092 {
1093 // Perform the actual substitution of template parameters within a new,
1094 // local instantiation scope.
1095 Sema::LocalInstantiationScope Scope(SemaRef);
1096 InstParams = SubstTemplateParams(TempParams);
1097 if (!InstParams)
1098 return NULL;
1099 }
1100
1101 // Build the template template parameter.
1102 TemplateTemplateParmDecl *Param
1103 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1104 D->getDepth() - 1, D->getPosition(),
1105 D->getIdentifier(), InstParams);
1106 Param->setDefaultArgument(D->getDefaultArgument());
1107
1108 // Introduce this template parameter's instantiation into the instantiation
1109 // scope.
1110 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1111
1112 return Param;
1113}
1114
Douglas Gregor48c32a72009-11-17 06:07:40 +00001115Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1116 // Using directives are never dependent, so they require no explicit
1117
1118 UsingDirectiveDecl *Inst
1119 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1120 D->getNamespaceKeyLocation(),
1121 D->getQualifierRange(), D->getQualifier(),
1122 D->getIdentLocation(),
1123 D->getNominatedNamespace(),
1124 D->getCommonAncestor());
1125 Owner->addDecl(Inst);
1126 return Inst;
1127}
1128
John McCalled976492009-12-04 22:46:56 +00001129Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1130 // The nested name specifier is non-dependent, so no transformation
1131 // is required.
1132
John McCall9f54ad42009-12-10 09:41:52 +00001133 // We only need to do redeclaration lookups if we're in a class
1134 // scope (in fact, it's not really even possible in non-class
1135 // scopes).
1136 bool CheckRedeclaration = Owner->isRecord();
1137
1138 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1139 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1140
John McCalled976492009-12-04 22:46:56 +00001141 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1142 D->getLocation(),
1143 D->getNestedNameRange(),
1144 D->getUsingLocation(),
1145 D->getTargetNestedNameDecl(),
1146 D->getDeclName(),
1147 D->isTypeName());
1148
1149 CXXScopeSpec SS;
1150 SS.setScopeRep(D->getTargetNestedNameDecl());
1151 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001152
1153 if (CheckRedeclaration) {
1154 Prev.setHideTags(false);
1155 SemaRef.LookupQualifiedName(Prev, Owner);
1156
1157 // Check for invalid redeclarations.
1158 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1159 D->isTypeName(), SS,
1160 D->getLocation(), Prev))
1161 NewUD->setInvalidDecl();
1162
1163 }
1164
1165 if (!NewUD->isInvalidDecl() &&
1166 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001167 D->getLocation()))
1168 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001169
John McCalled976492009-12-04 22:46:56 +00001170 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1171 NewUD->setAccess(D->getAccess());
1172 Owner->addDecl(NewUD);
1173
John McCall9f54ad42009-12-10 09:41:52 +00001174 // Don't process the shadow decls for an invalid decl.
1175 if (NewUD->isInvalidDecl())
1176 return NewUD;
1177
John McCall323c3102009-12-22 22:26:37 +00001178 bool isFunctionScope = Owner->isFunctionOrMethod();
1179
John McCall9f54ad42009-12-10 09:41:52 +00001180 // Process the shadow decls.
1181 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1182 I != E; ++I) {
1183 UsingShadowDecl *Shadow = *I;
1184 NamedDecl *InstTarget =
1185 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1186 TemplateArgs));
1187
1188 if (CheckRedeclaration &&
1189 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1190 continue;
1191
1192 UsingShadowDecl *InstShadow
1193 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1194 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001195
1196 if (isFunctionScope)
1197 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001198 }
John McCalled976492009-12-04 22:46:56 +00001199
1200 return NewUD;
1201}
1202
1203Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001204 // Ignore these; we handle them in bulk when processing the UsingDecl.
1205 return 0;
John McCalled976492009-12-04 22:46:56 +00001206}
1207
John McCall7ba107a2009-11-18 02:36:19 +00001208Decl * TemplateDeclInstantiator
1209 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001210 NestedNameSpecifier *NNS =
1211 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1212 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001213 TemplateArgs);
1214 if (!NNS)
1215 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001217 CXXScopeSpec SS;
1218 SS.setRange(D->getTargetNestedNameRange());
1219 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001220
1221 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001222 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001223 D->getUsingLoc(), SS, D->getLocation(),
1224 D->getDeclName(), 0,
1225 /*instantiation*/ true,
1226 /*typename*/ true, D->getTypenameLoc());
1227 if (UD)
John McCalled976492009-12-04 22:46:56 +00001228 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1229
John McCall7ba107a2009-11-18 02:36:19 +00001230 return UD;
1231}
1232
1233Decl * TemplateDeclInstantiator
1234 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1235 NestedNameSpecifier *NNS =
1236 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1237 D->getTargetNestedNameRange(),
1238 TemplateArgs);
1239 if (!NNS)
1240 return 0;
1241
1242 CXXScopeSpec SS;
1243 SS.setRange(D->getTargetNestedNameRange());
1244 SS.setScopeRep(NNS);
1245
1246 NamedDecl *UD =
1247 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1248 D->getUsingLoc(), SS, D->getLocation(),
1249 D->getDeclName(), 0,
1250 /*instantiation*/ true,
1251 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001252 if (UD)
John McCalled976492009-12-04 22:46:56 +00001253 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1254
Anders Carlsson0d8df782009-08-29 19:37:28 +00001255 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001256}
1257
John McCallce3ff2b2009-08-25 22:02:44 +00001258Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001259 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001260 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001261 return Instantiator.Visit(D);
1262}
1263
John McCalle29ba202009-08-20 01:44:21 +00001264/// \brief Instantiates a nested template parameter list in the current
1265/// instantiation context.
1266///
1267/// \param L The parameter list to instantiate
1268///
1269/// \returns NULL if there was an error
1270TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001271TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001272 // Get errors for all the parameters before bailing out.
1273 bool Invalid = false;
1274
1275 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001276 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001277 ParamVector Params;
1278 Params.reserve(N);
1279 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1280 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001281 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001282 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001283 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001284 }
1285
1286 // Clean up if we had an error.
1287 if (Invalid) {
1288 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1289 PI != PE; ++PI)
1290 if (*PI)
1291 (*PI)->Destroy(SemaRef.Context);
1292 return NULL;
1293 }
1294
1295 TemplateParameterList *InstL
1296 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1297 L->getLAngleLoc(), &Params.front(), N,
1298 L->getRAngleLoc());
1299 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001300}
John McCalle29ba202009-08-20 01:44:21 +00001301
Douglas Gregored9c0f92009-10-29 00:04:11 +00001302/// \brief Instantiate the declaration of a class template partial
1303/// specialization.
1304///
1305/// \param ClassTemplate the (instantiated) class template that is partially
1306// specialized by the instantiation of \p PartialSpec.
1307///
1308/// \param PartialSpec the (uninstantiated) class template partial
1309/// specialization that we are instantiating.
1310///
1311/// \returns true if there was an error, false otherwise.
1312bool
1313TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1314 ClassTemplateDecl *ClassTemplate,
1315 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001316 // Create a local instantiation scope for this class template partial
1317 // specialization, which will contain the instantiations of the template
1318 // parameters.
1319 Sema::LocalInstantiationScope Scope(SemaRef);
1320
Douglas Gregored9c0f92009-10-29 00:04:11 +00001321 // Substitute into the template parameters of the class template partial
1322 // specialization.
1323 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1324 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1325 if (!InstParams)
1326 return true;
1327
1328 // Substitute into the template arguments of the class template partial
1329 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001330 const TemplateArgumentLoc *PartialSpecTemplateArgs
1331 = PartialSpec->getTemplateArgsAsWritten();
1332 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1333
John McCalld5532b62009-11-23 01:53:49 +00001334 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001335 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001336 TemplateArgumentLoc Loc;
1337 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001338 return true;
John McCalld5532b62009-11-23 01:53:49 +00001339 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001340 }
1341
1342
1343 // Check that the template argument list is well-formed for this
1344 // class template.
1345 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1346 InstTemplateArgs.size());
1347 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1348 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001349 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001350 false,
1351 Converted))
1352 return true;
1353
1354 // Figure out where to insert this class template partial specialization
1355 // in the member template's set of class template partial specializations.
1356 llvm::FoldingSetNodeID ID;
1357 ClassTemplatePartialSpecializationDecl::Profile(ID,
1358 Converted.getFlatArguments(),
1359 Converted.flatSize(),
1360 SemaRef.Context);
1361 void *InsertPos = 0;
1362 ClassTemplateSpecializationDecl *PrevDecl
1363 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1364 InsertPos);
1365
1366 // Build the canonical type that describes the converted template
1367 // arguments of the class template partial specialization.
1368 QualType CanonType
1369 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1370 Converted.getFlatArguments(),
1371 Converted.flatSize());
1372
1373 // Build the fully-sugared type for this class template
1374 // specialization as the user wrote in the specialization
1375 // itself. This means that we'll pretty-print the type retrieved
1376 // from the specialization's declaration the way that the user
1377 // actually wrote the specialization, rather than formatting the
1378 // name based on the "canonical" representation used to store the
1379 // template arguments in the specialization.
1380 QualType WrittenTy
1381 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001382 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001383 CanonType);
1384
1385 if (PrevDecl) {
1386 // We've already seen a partial specialization with the same template
1387 // parameters and template arguments. This can happen, for example, when
1388 // substituting the outer template arguments ends up causing two
1389 // class template partial specializations of a member class template
1390 // to have identical forms, e.g.,
1391 //
1392 // template<typename T, typename U>
1393 // struct Outer {
1394 // template<typename X, typename Y> struct Inner;
1395 // template<typename Y> struct Inner<T, Y>;
1396 // template<typename Y> struct Inner<U, Y>;
1397 // };
1398 //
1399 // Outer<int, int> outer; // error: the partial specializations of Inner
1400 // // have the same signature.
1401 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1402 << WrittenTy;
1403 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1404 << SemaRef.Context.getTypeDeclType(PrevDecl);
1405 return true;
1406 }
1407
1408
1409 // Create the class template partial specialization declaration.
1410 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1411 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1412 PartialSpec->getLocation(),
1413 InstParams,
1414 ClassTemplate,
1415 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001416 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001417 0);
1418 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1419 InstPartialSpec->setTypeAsWritten(WrittenTy);
1420
1421 // Add this partial specialization to the set of class template partial
1422 // specializations.
1423 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1424 InsertPos);
1425 return false;
1426}
1427
John McCallce3ff2b2009-08-25 22:02:44 +00001428/// \brief Does substitution on the type of the given function, including
1429/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001430///
John McCallce3ff2b2009-08-25 22:02:44 +00001431/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001432///
1433/// \param Params the instantiated parameter declarations
1434
John McCallce3ff2b2009-08-25 22:02:44 +00001435/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001436/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001437QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001438TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001439 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1440 bool InvalidDecl = false;
1441
John McCallce3ff2b2009-08-25 22:02:44 +00001442 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001443 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001444 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001445 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001446 PEnd = D->param_end();
1447 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001448 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001449 if (PInst->getType()->isVoidType()) {
1450 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1451 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001452 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001453 PInst->getType(),
1454 diag::err_abstract_type_in_decl,
1455 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001456 PInst->setInvalidDecl();
1457
1458 Params.push_back(PInst);
1459 ParamTys.push_back(PInst->getType());
1460
1461 if (PInst->isInvalidDecl())
1462 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001463 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001464 InvalidDecl = true;
1465 }
1466
1467 // FIXME: Deallocate dead declarations.
1468 if (InvalidDecl)
1469 return QualType();
1470
John McCall183700f2009-09-21 23:43:11 +00001471 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001472 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001473 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001474 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1475 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001476 if (ResultType.isNull())
1477 return QualType();
1478
Jay Foadbeaaccd2009-05-21 09:52:38 +00001479 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001480 Proto->isVariadic(), Proto->getTypeQuals(),
1481 D->getLocation(), D->getDeclName());
1482}
1483
Mike Stump1eb44332009-09-09 15:08:12 +00001484/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001485/// declaration (New) from the corresponding fields of its template (Tmpl).
1486///
1487/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001488bool
1489TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001490 FunctionDecl *Tmpl) {
1491 if (Tmpl->isDeleted())
1492 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregorcca9e962009-07-01 22:01:06 +00001494 // If we are performing substituting explicitly-specified template arguments
1495 // or deduced template arguments into a function template and we reach this
1496 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001497 // to keeping the new function template specialization. We therefore
1498 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001499 // into a template instantiation for this specific function template
1500 // specialization, which is not a SFINAE context, so that we diagnose any
1501 // further errors in the declaration itself.
1502 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1503 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1504 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1505 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001506 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001507 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001508 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001509 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001510 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001511 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1512 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001513 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001514 }
1515 }
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001517 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1518 assert(Proto && "Function template without prototype?");
1519
1520 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1521 Proto->getNoReturnAttr()) {
1522 // The function has an exception specification or a "noreturn"
1523 // attribute. Substitute into each of the exception types.
1524 llvm::SmallVector<QualType, 4> Exceptions;
1525 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1526 // FIXME: Poor location information!
1527 QualType T
1528 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1529 New->getLocation(), New->getDeclName());
1530 if (T.isNull() ||
1531 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1532 continue;
1533
1534 Exceptions.push_back(T);
1535 }
1536
1537 // Rebuild the function type
1538
1539 const FunctionProtoType *NewProto
1540 = New->getType()->getAs<FunctionProtoType>();
1541 assert(NewProto && "Template instantiation without function prototype?");
1542 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1543 NewProto->arg_type_begin(),
1544 NewProto->getNumArgs(),
1545 NewProto->isVariadic(),
1546 NewProto->getTypeQuals(),
1547 Proto->hasExceptionSpec(),
1548 Proto->hasAnyExceptionSpec(),
1549 Exceptions.size(),
1550 Exceptions.data(),
1551 Proto->getNoReturnAttr()));
1552 }
1553
Douglas Gregore53060f2009-06-25 22:08:12 +00001554 return false;
1555}
1556
Douglas Gregor5545e162009-03-24 00:38:23 +00001557/// \brief Initializes common fields of an instantiated method
1558/// declaration (New) from the corresponding fields of its template
1559/// (Tmpl).
1560///
1561/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001562bool
1563TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001564 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001565 if (InitFunctionInstantiation(New, Tmpl))
1566 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregor5545e162009-03-24 00:38:23 +00001568 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1569 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001570 if (Tmpl->isVirtualAsWritten())
1571 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001572
1573 // FIXME: attributes
1574 // FIXME: New needs a pointer to Tmpl
1575 return false;
1576}
Douglas Gregora58861f2009-05-13 20:28:22 +00001577
1578/// \brief Instantiate the definition of the given function from its
1579/// template.
1580///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001581/// \param PointOfInstantiation the point at which the instantiation was
1582/// required. Note that this is not precisely a "point of instantiation"
1583/// for the function, but it's close.
1584///
Douglas Gregora58861f2009-05-13 20:28:22 +00001585/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001586/// function template specialization or member function of a class template
1587/// specialization.
1588///
1589/// \param Recursive if true, recursively instantiates any functions that
1590/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001591///
1592/// \param DefinitionRequired if true, then we are performing an explicit
1593/// instantiation where the body of the function is required. Complain if
1594/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001595void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001596 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001597 bool Recursive,
1598 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001599 if (Function->isInvalidDecl())
1600 return;
1601
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001602 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001604 // Never instantiate an explicit specialization.
1605 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1606 return;
1607
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001608 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001609 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001610 Stmt *Pattern = 0;
1611 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001612 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001613
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001614 if (!Pattern) {
1615 if (DefinitionRequired) {
1616 if (Function->getPrimaryTemplate())
1617 Diag(PointOfInstantiation,
1618 diag::err_explicit_instantiation_undefined_func_template)
1619 << Function->getPrimaryTemplate();
1620 else
1621 Diag(PointOfInstantiation,
1622 diag::err_explicit_instantiation_undefined_member)
1623 << 1 << Function->getDeclName() << Function->getDeclContext();
1624
1625 if (PatternDecl)
1626 Diag(PatternDecl->getLocation(),
1627 diag::note_explicit_instantiation_here);
1628 }
1629
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001630 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001631 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001632
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001633 // C++0x [temp.explicit]p9:
1634 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001635 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001636 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001637 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001638 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001639 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001640 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001642 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1643 if (Inst)
1644 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001645
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001646 // If we're performing recursive template instantiation, create our own
1647 // queue of pending implicit instantiations that we will instantiate later,
1648 // while we're still within our own instantiation context.
1649 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1650 if (Recursive)
1651 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001653 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1654
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001655 // Introduce a new scope where local variable instantiations will be
1656 // recorded.
1657 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001659 // Introduce the instantiated function parameters into the local
1660 // instantiation scope.
1661 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1662 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1663 Function->getParamDecl(I));
1664
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001665 // Enter the scope of this instantiation. We don't use
1666 // PushDeclContext because we don't have a scope.
1667 DeclContext *PreviousContext = CurContext;
1668 CurContext = Function;
1669
Mike Stump1eb44332009-09-09 15:08:12 +00001670 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001671 getTemplateInstantiationArgs(Function);
1672
1673 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001674 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001675 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1676 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1677 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001678 }
1679
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001680 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001681 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001682
Douglas Gregor52604ab2009-09-11 21:19:12 +00001683 if (Body.isInvalid())
1684 Function->setInvalidDecl();
1685
Mike Stump1eb44332009-09-09 15:08:12 +00001686 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001687 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001688
1689 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001690
1691 DeclGroupRef DG(Function);
1692 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001694 if (Recursive) {
1695 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001696 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001697 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001699 // Restore the set of pending implicit instantiations.
1700 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1701 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001702}
1703
1704/// \brief Instantiate the definition of the given variable from its
1705/// template.
1706///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001707/// \param PointOfInstantiation the point at which the instantiation was
1708/// required. Note that this is not precisely a "point of instantiation"
1709/// for the function, but it's close.
1710///
1711/// \param Var the already-instantiated declaration of a static member
1712/// variable of a class template specialization.
1713///
1714/// \param Recursive if true, recursively instantiates any functions that
1715/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001716///
1717/// \param DefinitionRequired if true, then we are performing an explicit
1718/// instantiation where an out-of-line definition of the member variable
1719/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001720void Sema::InstantiateStaticDataMemberDefinition(
1721 SourceLocation PointOfInstantiation,
1722 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001723 bool Recursive,
1724 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001725 if (Var->isInvalidDecl())
1726 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Douglas Gregor7caa6822009-07-24 20:34:43 +00001728 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001729 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001730 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001731 assert(Def->isStaticDataMember() && "Not a static data member?");
1732 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Douglas Gregor0d035142009-10-27 18:42:08 +00001734 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001735 // We did not find an out-of-line definition of this static data member,
1736 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001737 // instantiate this definition (or provide a specialization for it) in
1738 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001739 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001740 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001741 Diag(PointOfInstantiation,
1742 diag::err_explicit_instantiation_undefined_member)
1743 << 2 << Var->getDeclName() << Var->getDeclContext();
1744 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1745 }
1746
Douglas Gregor7caa6822009-07-24 20:34:43 +00001747 return;
1748 }
1749
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001750 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001751 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001752 return;
1753
1754 // C++0x [temp.explicit]p9:
1755 // Except for inline functions, other explicit instantiation declarations
1756 // have the effect of suppressing the implicit instantiation of the entity
1757 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001758 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001759 == TSK_ExplicitInstantiationDeclaration)
1760 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor7caa6822009-07-24 20:34:43 +00001762 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1763 if (Inst)
1764 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Douglas Gregor7caa6822009-07-24 20:34:43 +00001766 // If we're performing recursive template instantiation, create our own
1767 // queue of pending implicit instantiations that we will instantiate later,
1768 // while we're still within our own instantiation context.
1769 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1770 if (Recursive)
1771 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Douglas Gregor7caa6822009-07-24 20:34:43 +00001773 // Enter the scope of this instantiation. We don't use
1774 // PushDeclContext because we don't have a scope.
1775 DeclContext *PreviousContext = CurContext;
1776 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001778 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001779 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001780 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001781 CurContext = PreviousContext;
1782
1783 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001784 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001785 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1786 assert(MSInfo && "Missing member specialization information?");
1787 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1788 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001789 DeclGroupRef DG(Var);
1790 Consumer.HandleTopLevelDecl(DG);
1791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Douglas Gregor7caa6822009-07-24 20:34:43 +00001793 if (Recursive) {
1794 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001795 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001796 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Douglas Gregor7caa6822009-07-24 20:34:43 +00001798 // Restore the set of pending implicit instantiations.
1799 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001800 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001801}
Douglas Gregor815215d2009-05-27 05:35:12 +00001802
Anders Carlsson09025312009-08-29 05:16:22 +00001803void
1804Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1805 const CXXConstructorDecl *Tmpl,
1806 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anders Carlsson09025312009-08-29 05:16:22 +00001808 llvm::SmallVector<MemInitTy*, 4> NewInits;
1809
1810 // Instantiate all the initializers.
1811 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001812 InitsEnd = Tmpl->init_end();
1813 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001814 CXXBaseOrMemberInitializer *Init = *Inits;
1815
1816 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Anders Carlsson09025312009-08-29 05:16:22 +00001818 // Instantiate all the arguments.
1819 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1820 Args != ArgsEnd; ++Args) {
1821 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1822
1823 if (NewArg.isInvalid())
1824 New->setInvalidDecl();
1825 else
1826 NewArgs.push_back(NewArg.takeAs<Expr>());
1827 }
1828
1829 MemInitResult NewInit;
1830
1831 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001832 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001833 TemplateArgs,
1834 Init->getSourceLocation(),
1835 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001836 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001837 New->setInvalidDecl();
1838 continue;
1839 }
1840
John McCalla93c9342009-12-07 02:54:59 +00001841 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001842 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001843 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001844 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001845 Init->getRParenLoc(),
1846 New->getParent());
1847 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001848 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001850 // Is this an anonymous union?
1851 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001852 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001853 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001854 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1855 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001856
1857 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001858 NewArgs.size(),
1859 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001860 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001861 Init->getRParenLoc());
1862 }
1863
1864 if (NewInit.isInvalid())
1865 New->setInvalidDecl();
1866 else {
1867 // FIXME: It would be nice if ASTOwningVector had a release function.
1868 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Anders Carlsson09025312009-08-29 05:16:22 +00001870 NewInits.push_back((MemInitTy *)NewInit.get());
1871 }
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Anders Carlsson09025312009-08-29 05:16:22 +00001874 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001876 /*FIXME: ColonLoc */
1877 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001878 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001879}
1880
John McCall52a575a2009-08-29 08:11:13 +00001881// TODO: this could be templated if the various decl types used the
1882// same method name.
1883static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1884 ClassTemplateDecl *Instance) {
1885 Pattern = Pattern->getCanonicalDecl();
1886
1887 do {
1888 Instance = Instance->getCanonicalDecl();
1889 if (Pattern == Instance) return true;
1890 Instance = Instance->getInstantiatedFromMemberTemplate();
1891 } while (Instance);
1892
1893 return false;
1894}
1895
Douglas Gregor0d696532009-09-28 06:34:35 +00001896static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1897 FunctionTemplateDecl *Instance) {
1898 Pattern = Pattern->getCanonicalDecl();
1899
1900 do {
1901 Instance = Instance->getCanonicalDecl();
1902 if (Pattern == Instance) return true;
1903 Instance = Instance->getInstantiatedFromMemberTemplate();
1904 } while (Instance);
1905
1906 return false;
1907}
1908
Douglas Gregored9c0f92009-10-29 00:04:11 +00001909static bool
1910isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1911 ClassTemplatePartialSpecializationDecl *Instance) {
1912 Pattern
1913 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1914 do {
1915 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1916 Instance->getCanonicalDecl());
1917 if (Pattern == Instance)
1918 return true;
1919 Instance = Instance->getInstantiatedFromMember();
1920 } while (Instance);
1921
1922 return false;
1923}
1924
John McCall52a575a2009-08-29 08:11:13 +00001925static bool isInstantiationOf(CXXRecordDecl *Pattern,
1926 CXXRecordDecl *Instance) {
1927 Pattern = Pattern->getCanonicalDecl();
1928
1929 do {
1930 Instance = Instance->getCanonicalDecl();
1931 if (Pattern == Instance) return true;
1932 Instance = Instance->getInstantiatedFromMemberClass();
1933 } while (Instance);
1934
1935 return false;
1936}
1937
1938static bool isInstantiationOf(FunctionDecl *Pattern,
1939 FunctionDecl *Instance) {
1940 Pattern = Pattern->getCanonicalDecl();
1941
1942 do {
1943 Instance = Instance->getCanonicalDecl();
1944 if (Pattern == Instance) return true;
1945 Instance = Instance->getInstantiatedFromMemberFunction();
1946 } while (Instance);
1947
1948 return false;
1949}
1950
1951static bool isInstantiationOf(EnumDecl *Pattern,
1952 EnumDecl *Instance) {
1953 Pattern = Pattern->getCanonicalDecl();
1954
1955 do {
1956 Instance = Instance->getCanonicalDecl();
1957 if (Pattern == Instance) return true;
1958 Instance = Instance->getInstantiatedFromMemberEnum();
1959 } while (Instance);
1960
1961 return false;
1962}
1963
John McCalled976492009-12-04 22:46:56 +00001964static bool isInstantiationOf(UsingShadowDecl *Pattern,
1965 UsingShadowDecl *Instance,
1966 ASTContext &C) {
1967 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1968}
1969
1970static bool isInstantiationOf(UsingDecl *Pattern,
1971 UsingDecl *Instance,
1972 ASTContext &C) {
1973 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1974}
1975
John McCall7ba107a2009-11-18 02:36:19 +00001976static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1977 UsingDecl *Instance,
1978 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001979 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001980}
1981
1982static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001983 UsingDecl *Instance,
1984 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001985 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001986}
1987
John McCall52a575a2009-08-29 08:11:13 +00001988static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1989 VarDecl *Instance) {
1990 assert(Instance->isStaticDataMember());
1991
1992 Pattern = Pattern->getCanonicalDecl();
1993
1994 do {
1995 Instance = Instance->getCanonicalDecl();
1996 if (Pattern == Instance) return true;
1997 Instance = Instance->getInstantiatedFromStaticDataMember();
1998 } while (Instance);
1999
2000 return false;
2001}
2002
John McCalled976492009-12-04 22:46:56 +00002003// Other is the prospective instantiation
2004// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002005static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002006 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002007 if (UnresolvedUsingTypenameDecl *UUD
2008 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2009 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2010 return isInstantiationOf(UUD, UD, Ctx);
2011 }
2012 }
2013
2014 if (UnresolvedUsingValueDecl *UUD
2015 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002016 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2017 return isInstantiationOf(UUD, UD, Ctx);
2018 }
2019 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002020
Anders Carlsson0d8df782009-08-29 19:37:28 +00002021 return false;
2022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
John McCall52a575a2009-08-29 08:11:13 +00002024 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2025 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
John McCall52a575a2009-08-29 08:11:13 +00002027 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2028 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002029
John McCall52a575a2009-08-29 08:11:13 +00002030 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2031 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002032
Douglas Gregor7caa6822009-07-24 20:34:43 +00002033 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002034 if (Var->isStaticDataMember())
2035 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2036
2037 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2038 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002039
Douglas Gregor0d696532009-09-28 06:34:35 +00002040 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2041 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2042
Douglas Gregored9c0f92009-10-29 00:04:11 +00002043 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2044 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2045 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2046 PartialSpec);
2047
Anders Carlssond8b285f2009-09-01 04:26:58 +00002048 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2049 if (!Field->getDeclName()) {
2050 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002051 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002052 cast<FieldDecl>(D);
2053 }
2054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John McCalled976492009-12-04 22:46:56 +00002056 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2057 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2058
2059 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2060 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2061
Douglas Gregor815215d2009-05-27 05:35:12 +00002062 return D->getDeclName() && isa<NamedDecl>(Other) &&
2063 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2064}
2065
2066template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002067static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002068 NamedDecl *D,
2069 ForwardIterator first,
2070 ForwardIterator last) {
2071 for (; first != last; ++first)
2072 if (isInstantiationOf(Ctx, D, *first))
2073 return cast<NamedDecl>(*first);
2074
2075 return 0;
2076}
2077
John McCall02cace72009-08-28 07:59:38 +00002078/// \brief Finds the instantiation of the given declaration context
2079/// within the current instantiation.
2080///
2081/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002082DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2083 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002084 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002085 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002086 return cast_or_null<DeclContext>(ID);
2087 } else return DC;
2088}
2089
Douglas Gregored961e72009-05-27 17:54:46 +00002090/// \brief Find the instantiation of the given declaration within the
2091/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002092///
2093/// This routine is intended to be used when \p D is a declaration
2094/// referenced from within a template, that needs to mapped into the
2095/// corresponding declaration within an instantiation. For example,
2096/// given:
2097///
2098/// \code
2099/// template<typename T>
2100/// struct X {
2101/// enum Kind {
2102/// KnownValue = sizeof(T)
2103/// };
2104///
2105/// bool getKind() const { return KnownValue; }
2106/// };
2107///
2108/// template struct X<int>;
2109/// \endcode
2110///
2111/// In the instantiation of X<int>::getKind(), we need to map the
2112/// EnumConstantDecl for KnownValue (which refers to
2113/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002114/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2115/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002116NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2117 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002118 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002119 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2120 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2121 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002122 // D is a local of some kind. Look into the map of local
2123 // declarations to their instantiations.
2124 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2125 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002126
Douglas Gregore95b4092009-09-16 18:34:49 +00002127 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2128 if (!Record->isDependentContext())
2129 return D;
2130
2131 // If the RecordDecl is actually the injected-class-name or a "templated"
2132 // declaration for a class template or class template partial
2133 // specialization, substitute into the injected-class-name of the
2134 // class template or partial specialization to find the new DeclContext.
2135 QualType T;
2136 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2137
2138 if (ClassTemplate) {
2139 T = ClassTemplate->getInjectedClassNameType(Context);
2140 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2141 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2142 T = Context.getTypeDeclType(Record);
2143 ClassTemplate = PartialSpec->getSpecializedTemplate();
2144 }
2145
2146 if (!T.isNull()) {
2147 // Substitute into the injected-class-name to get the type corresponding
2148 // to the instantiation we want. This substitution should never fail,
2149 // since we know we can instantiate the injected-class-name or we wouldn't
2150 // have gotten to the injected-class-name!
2151 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2152 // instantiation in the common case?
2153 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2154 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2155
2156 if (!T->isDependentType()) {
2157 assert(T->isRecordType() && "Instantiation must produce a record type");
2158 return T->getAs<RecordType>()->getDecl();
2159 }
2160
2161 // We are performing "partial" template instantiation to create the
2162 // member declarations for the members of a class template
2163 // specialization. Therefore, D is actually referring to something in
2164 // the current instantiation. Look through the current context,
2165 // which contains actual instantiations, to find the instantiation of
2166 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002168 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002169 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002170 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002171 if (isInstantiationOf(ClassTemplate,
2172 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002173 return Spec;
2174 }
2175
Mike Stump1eb44332009-09-09 15:08:12 +00002176 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002177 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002178 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002179 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002180
2181 // Fall through to deal with other dependent record types (e.g.,
2182 // anonymous unions in class templates).
2183 }
John McCall52a575a2009-08-29 08:11:13 +00002184
Douglas Gregore95b4092009-09-16 18:34:49 +00002185 if (!ParentDC->isDependentContext())
2186 return D;
2187
2188 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002189 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002190 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Douglas Gregor815215d2009-05-27 05:35:12 +00002192 if (ParentDC != D->getDeclContext()) {
2193 // We performed some kind of instantiation in the parent context,
2194 // so now we need to look into the instantiated parent context to
2195 // find the instantiation of the declaration D.
2196 NamedDecl *Result = 0;
2197 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002198 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002199 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2200 } else {
2201 // Since we don't have a name for the entity we're looking for,
2202 // our only option is to walk through all of the declarations to
2203 // find that name. This will occur in a few cases:
2204 //
2205 // - anonymous struct/union within a template
2206 // - unnamed class/struct/union/enum within a template
2207 //
2208 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002209 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002210 ParentDC->decls_begin(),
2211 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002212 }
Mike Stump1eb44332009-09-09 15:08:12 +00002213
John McCall9f54ad42009-12-10 09:41:52 +00002214 // UsingShadowDecls can instantiate to nothing because of using hiding.
2215 assert((Result || isa<UsingShadowDecl>(D))
2216 && "Unable to find instantiation of declaration!");
2217
Douglas Gregor815215d2009-05-27 05:35:12 +00002218 D = Result;
2219 }
2220
Douglas Gregor815215d2009-05-27 05:35:12 +00002221 return D;
2222}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002223
Mike Stump1eb44332009-09-09 15:08:12 +00002224/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002225/// instantiations we have seen until this point.
2226void Sema::PerformPendingImplicitInstantiations() {
2227 while (!PendingImplicitInstantiations.empty()) {
2228 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002229 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor7caa6822009-07-24 20:34:43 +00002231 // Instantiate function definitions
2232 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002233 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002234 Function->getLocation(), *this,
2235 Context.getSourceManager(),
2236 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002238 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002239 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002240 continue;
2241 }
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Douglas Gregor7caa6822009-07-24 20:34:43 +00002243 // Instantiate static data member definitions.
2244 VarDecl *Var = cast<VarDecl>(Inst.first);
2245 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002246
Mike Stump1eb44332009-09-09 15:08:12 +00002247 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002248 Var->getLocation(), *this,
2249 Context.getSourceManager(),
2250 "instantiating static data member "
2251 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Douglas Gregor7caa6822009-07-24 20:34:43 +00002253 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002254 }
2255}