blob: e909c4f0b9b6761e99e5cae58942c3a229315755 [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 Gregor550d9b22009-10-31 17:21:17 +0000720 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Douglas Gregore53060f2009-06-25 22:08:12 +0000722 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000723 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000724 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000725 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000726
Douglas Gregore53060f2009-06-25 22:08:12 +0000727 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000728 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
729 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000730 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000731 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000732 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000733 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000734 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000735 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Douglas Gregore53060f2009-06-25 22:08:12 +0000737 // Attach the parameters
738 for (unsigned P = 0; P < Params.size(); ++P)
739 Params[P]->setOwningFunction(Function);
740 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000741
Douglas Gregora735b202009-10-13 14:39:41 +0000742 if (TemplateParams) {
743 // Our resulting instantiation is actually a function template, since we
744 // are substituting only the outer template parameters. For example, given
745 //
746 // template<typename T>
747 // struct X {
748 // template<typename U> friend void f(T, U);
749 // };
750 //
751 // X<int> x;
752 //
753 // We are instantiating the friend function template "f" within X<int>,
754 // which means substituting int for T, but leaving "f" as a friend function
755 // template.
756 // Build the function template itself.
757 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
758 Function->getLocation(),
759 Function->getDeclName(),
760 TemplateParams, Function);
761 Function->setDescribedFunctionTemplate(FunctionTemplate);
762 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000763 } else if (FunctionTemplate) {
764 // Record this function template specialization.
765 Function->setFunctionTemplateSpecialization(SemaRef.Context,
766 FunctionTemplate,
767 &TemplateArgs.getInnermost(),
768 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000769 }
Douglas Gregora735b202009-10-13 14:39:41 +0000770
Douglas Gregore53060f2009-06-25 22:08:12 +0000771 if (InitFunctionInstantiation(Function, D))
772 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregore53060f2009-06-25 22:08:12 +0000774 bool Redeclaration = false;
775 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000776
John McCall68263142009-11-18 22:49:29 +0000777 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
778 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
779
Douglas Gregora735b202009-10-13 14:39:41 +0000780 if (TemplateParams || !FunctionTemplate) {
781 // Look only into the namespace where the friend would be declared to
782 // find a previous declaration. This is the innermost enclosing namespace,
783 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000784 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000785
Douglas Gregora735b202009-10-13 14:39:41 +0000786 // In C++, the previous declaration we find might be a tag type
787 // (class or enum). In this case, the new declaration will hide the
788 // tag type. Note that this does does not apply if we're declaring a
789 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000790 if (Previous.isSingleTagDecl())
791 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000792 }
793
John McCall9f54ad42009-12-10 09:41:52 +0000794 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
795 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000796 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000797
Douglas Gregora735b202009-10-13 14:39:41 +0000798 // If the original function was part of a friend declaration,
799 // inherit its namespace state and add it to the owner.
800 NamedDecl *FromFriendD
801 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
802 if (FromFriendD->getFriendObjectKind()) {
803 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000804 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000805 if (TemplateParams) {
806 ToFriendD = cast<NamedDecl>(FunctionTemplate);
807 PrevDecl = FunctionTemplate->getPreviousDeclaration();
808 } else {
809 ToFriendD = Function;
810 PrevDecl = Function->getPreviousDeclaration();
811 }
812 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
813 if (!Owner->isDependentContext() && !PrevDecl)
814 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
815
816 if (!TemplateParams)
817 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
818 }
819
Douglas Gregore53060f2009-06-25 22:08:12 +0000820 return Function;
821}
822
Douglas Gregord60e1052009-08-27 16:57:43 +0000823Decl *
824TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
825 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000826 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
827 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000828 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000829 // We are creating a function template specialization from a function
830 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000831 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000832 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000833 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000834 TemplateArgs.getInnermost().getFlatArgumentList(),
835 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000836 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000837
838 FunctionTemplateSpecializationInfo *Info
839 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000840 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Douglas Gregor6b906862009-08-21 00:16:32 +0000842 // If we already have a function template specialization, return it.
843 if (Info)
844 return Info->Function;
845 }
846
Douglas Gregor550d9b22009-10-31 17:21:17 +0000847 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000848
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000849 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000850 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000851 if (T.isNull())
852 return 0;
853
854 // Build the instantiated method declaration.
855 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000856 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregordec06662009-08-21 18:42:58 +0000858 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000859 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000860 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
861 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
862 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000863 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
864 Constructor->getLocation(),
865 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000866 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000867 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000868 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000869 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
870 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
871 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
872 SemaRef.Context.getCanonicalType(ClassTy));
873 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
874 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000875 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000876 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000877 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000878 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000879 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000880 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
881 ConvTy);
882 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
883 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000884 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000885 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000886 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000887 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000888 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000889 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000890 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000891 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000892
Douglas Gregord60e1052009-08-27 16:57:43 +0000893 if (TemplateParams) {
894 // Our resulting instantiation is actually a function template, since we
895 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000896 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000897 // template<typename T>
898 // struct X {
899 // template<typename U> void f(T, U);
900 // };
901 //
902 // X<int> x;
903 //
904 // We are instantiating the member template "f" within X<int>, which means
905 // substituting int for T, but leaving "f" as a member function template.
906 // Build the function template itself.
907 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
908 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000909 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000910 TemplateParams, Method);
911 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000912 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000913 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000914 } else if (FunctionTemplate) {
915 // Record this function template specialization.
916 Method->setFunctionTemplateSpecialization(SemaRef.Context,
917 FunctionTemplate,
918 &TemplateArgs.getInnermost(),
919 InsertPos);
920 } else {
921 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000922 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000923 }
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000926 // out-of-line, the instantiation will have the same lexical
927 // context (which will be a namespace scope) as the template.
928 if (D->isOutOfLine())
929 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregor5545e162009-03-24 00:38:23 +0000931 // Attach the parameters
932 for (unsigned P = 0; P < Params.size(); ++P)
933 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000934 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000935
936 if (InitMethodInstantiation(Method, D))
937 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000938
John McCall68263142009-11-18 22:49:29 +0000939 LookupResult Previous(SemaRef, Name, SourceLocation(),
940 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregord60e1052009-08-27 16:57:43 +0000942 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000943 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Douglas Gregordec06662009-08-21 18:42:58 +0000945 // In C++, the previous declaration we find might be a tag type
946 // (class or enum). In this case, the new declaration will hide the
947 // tag type. Note that this does does not apply if we're declaring a
948 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000949 if (Previous.isSingleTagDecl())
950 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000951 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000952
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000953 bool Redeclaration = false;
954 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000955 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000956 /*FIXME:*/OverloadableAttrRequired);
957
Douglas Gregor4ba31362009-12-01 17:24:26 +0000958 if (D->isPure())
959 SemaRef.CheckPureMethod(Method, SourceRange());
960
John McCall68263142009-11-18 22:49:29 +0000961 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000962 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000963 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000965 return Method;
966}
967
Douglas Gregor615c5d42009-03-24 16:43:20 +0000968Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000969 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000970}
971
Douglas Gregor03b2b072009-03-24 00:15:49 +0000972Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000973 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000974}
975
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000976Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000977 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000978}
979
Douglas Gregor6477b692009-03-25 15:04:13 +0000980ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000981 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000982 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000983 if (DI) {
984 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
985 D->getDeclName());
986 if (DI) T = DI->getType();
987 } else {
988 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
989 D->getDeclName());
990 DI = 0;
991 }
992
993 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000994 return 0;
995
John McCall58e46772009-10-23 21:48:59 +0000996 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000997
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000998 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000999 ParmVarDecl *Param
1000 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1001 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001002
Anders Carlsson9351c172009-08-25 03:18:48 +00001003 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001004 if (D->hasUninstantiatedDefaultArg())
1005 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001006 else if (Expr *Arg = D->getDefaultArg())
1007 Param->setUninstantiatedDefaultArg(Arg);
1008
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001009 // Note: we don't try to instantiate function parameters until after
1010 // we've instantiated the function's type. Therefore, we don't have
1011 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001012 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001013 return Param;
1014}
1015
John McCalle29ba202009-08-20 01:44:21 +00001016Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1017 TemplateTypeParmDecl *D) {
1018 // TODO: don't always clone when decls are refcounted.
1019 const Type* T = D->getTypeForDecl();
1020 assert(T->isTemplateTypeParmType());
1021 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
John McCalle29ba202009-08-20 01:44:21 +00001023 TemplateTypeParmDecl *Inst =
1024 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001025 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001026 TTPT->getName(),
1027 D->wasDeclaredWithTypename(),
1028 D->isParameterPack());
1029
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001030 if (D->hasDefaultArgument())
1031 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001032
Douglas Gregor550d9b22009-10-31 17:21:17 +00001033 // Introduce this template parameter's instantiation into the instantiation
1034 // scope.
1035 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1036
John McCalle29ba202009-08-20 01:44:21 +00001037 return Inst;
1038}
1039
Douglas Gregor33642df2009-10-23 23:25:44 +00001040Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1041 NonTypeTemplateParmDecl *D) {
1042 // Substitute into the type of the non-type template parameter.
1043 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001044 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001045 if (DI) {
1046 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1047 D->getDeclName());
1048 if (DI) T = DI->getType();
1049 } else {
1050 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1051 D->getDeclName());
1052 DI = 0;
1053 }
1054 if (T.isNull())
1055 return 0;
1056
1057 // Check that this type is acceptable for a non-type template parameter.
1058 bool Invalid = false;
1059 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1060 if (T.isNull()) {
1061 T = SemaRef.Context.IntTy;
1062 Invalid = true;
1063 }
1064
1065 NonTypeTemplateParmDecl *Param
1066 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1067 D->getDepth() - 1, D->getPosition(),
1068 D->getIdentifier(), T, DI);
1069 if (Invalid)
1070 Param->setInvalidDecl();
1071
1072 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001073
1074 // Introduce this template parameter's instantiation into the instantiation
1075 // scope.
1076 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001077 return Param;
1078}
1079
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001080Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001081TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1082 TemplateTemplateParmDecl *D) {
1083 // Instantiate the template parameter list of the template template parameter.
1084 TemplateParameterList *TempParams = D->getTemplateParameters();
1085 TemplateParameterList *InstParams;
1086 {
1087 // Perform the actual substitution of template parameters within a new,
1088 // local instantiation scope.
1089 Sema::LocalInstantiationScope Scope(SemaRef);
1090 InstParams = SubstTemplateParams(TempParams);
1091 if (!InstParams)
1092 return NULL;
1093 }
1094
1095 // Build the template template parameter.
1096 TemplateTemplateParmDecl *Param
1097 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1098 D->getDepth() - 1, D->getPosition(),
1099 D->getIdentifier(), InstParams);
1100 Param->setDefaultArgument(D->getDefaultArgument());
1101
1102 // Introduce this template parameter's instantiation into the instantiation
1103 // scope.
1104 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1105
1106 return Param;
1107}
1108
Douglas Gregor48c32a72009-11-17 06:07:40 +00001109Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1110 // Using directives are never dependent, so they require no explicit
1111
1112 UsingDirectiveDecl *Inst
1113 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1114 D->getNamespaceKeyLocation(),
1115 D->getQualifierRange(), D->getQualifier(),
1116 D->getIdentLocation(),
1117 D->getNominatedNamespace(),
1118 D->getCommonAncestor());
1119 Owner->addDecl(Inst);
1120 return Inst;
1121}
1122
John McCalled976492009-12-04 22:46:56 +00001123Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1124 // The nested name specifier is non-dependent, so no transformation
1125 // is required.
1126
John McCall9f54ad42009-12-10 09:41:52 +00001127 // We only need to do redeclaration lookups if we're in a class
1128 // scope (in fact, it's not really even possible in non-class
1129 // scopes).
1130 bool CheckRedeclaration = Owner->isRecord();
1131
1132 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1133 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1134
John McCalled976492009-12-04 22:46:56 +00001135 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1136 D->getLocation(),
1137 D->getNestedNameRange(),
1138 D->getUsingLocation(),
1139 D->getTargetNestedNameDecl(),
1140 D->getDeclName(),
1141 D->isTypeName());
1142
1143 CXXScopeSpec SS;
1144 SS.setScopeRep(D->getTargetNestedNameDecl());
1145 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001146
1147 if (CheckRedeclaration) {
1148 Prev.setHideTags(false);
1149 SemaRef.LookupQualifiedName(Prev, Owner);
1150
1151 // Check for invalid redeclarations.
1152 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1153 D->isTypeName(), SS,
1154 D->getLocation(), Prev))
1155 NewUD->setInvalidDecl();
1156
1157 }
1158
1159 if (!NewUD->isInvalidDecl() &&
1160 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001161 D->getLocation()))
1162 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001163
John McCalled976492009-12-04 22:46:56 +00001164 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1165 NewUD->setAccess(D->getAccess());
1166 Owner->addDecl(NewUD);
1167
John McCall9f54ad42009-12-10 09:41:52 +00001168 // Don't process the shadow decls for an invalid decl.
1169 if (NewUD->isInvalidDecl())
1170 return NewUD;
1171
John McCall323c3102009-12-22 22:26:37 +00001172 bool isFunctionScope = Owner->isFunctionOrMethod();
1173
John McCall9f54ad42009-12-10 09:41:52 +00001174 // Process the shadow decls.
1175 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1176 I != E; ++I) {
1177 UsingShadowDecl *Shadow = *I;
1178 NamedDecl *InstTarget =
1179 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1180 TemplateArgs));
1181
1182 if (CheckRedeclaration &&
1183 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1184 continue;
1185
1186 UsingShadowDecl *InstShadow
1187 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1188 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001189
1190 if (isFunctionScope)
1191 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001192 }
John McCalled976492009-12-04 22:46:56 +00001193
1194 return NewUD;
1195}
1196
1197Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001198 // Ignore these; we handle them in bulk when processing the UsingDecl.
1199 return 0;
John McCalled976492009-12-04 22:46:56 +00001200}
1201
John McCall7ba107a2009-11-18 02:36:19 +00001202Decl * TemplateDeclInstantiator
1203 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001204 NestedNameSpecifier *NNS =
1205 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1206 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001207 TemplateArgs);
1208 if (!NNS)
1209 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001211 CXXScopeSpec SS;
1212 SS.setRange(D->getTargetNestedNameRange());
1213 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
1215 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001216 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001217 D->getUsingLoc(), SS, D->getLocation(),
1218 D->getDeclName(), 0,
1219 /*instantiation*/ true,
1220 /*typename*/ true, D->getTypenameLoc());
1221 if (UD)
John McCalled976492009-12-04 22:46:56 +00001222 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1223
John McCall7ba107a2009-11-18 02:36:19 +00001224 return UD;
1225}
1226
1227Decl * TemplateDeclInstantiator
1228 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1229 NestedNameSpecifier *NNS =
1230 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1231 D->getTargetNestedNameRange(),
1232 TemplateArgs);
1233 if (!NNS)
1234 return 0;
1235
1236 CXXScopeSpec SS;
1237 SS.setRange(D->getTargetNestedNameRange());
1238 SS.setScopeRep(NNS);
1239
1240 NamedDecl *UD =
1241 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1242 D->getUsingLoc(), SS, D->getLocation(),
1243 D->getDeclName(), 0,
1244 /*instantiation*/ true,
1245 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001246 if (UD)
John McCalled976492009-12-04 22:46:56 +00001247 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1248
Anders Carlsson0d8df782009-08-29 19:37:28 +00001249 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001250}
1251
John McCallce3ff2b2009-08-25 22:02:44 +00001252Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001253 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001254 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001255 return Instantiator.Visit(D);
1256}
1257
John McCalle29ba202009-08-20 01:44:21 +00001258/// \brief Instantiates a nested template parameter list in the current
1259/// instantiation context.
1260///
1261/// \param L The parameter list to instantiate
1262///
1263/// \returns NULL if there was an error
1264TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001265TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001266 // Get errors for all the parameters before bailing out.
1267 bool Invalid = false;
1268
1269 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001270 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001271 ParamVector Params;
1272 Params.reserve(N);
1273 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1274 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001275 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001276 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001277 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001278 }
1279
1280 // Clean up if we had an error.
1281 if (Invalid) {
1282 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1283 PI != PE; ++PI)
1284 if (*PI)
1285 (*PI)->Destroy(SemaRef.Context);
1286 return NULL;
1287 }
1288
1289 TemplateParameterList *InstL
1290 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1291 L->getLAngleLoc(), &Params.front(), N,
1292 L->getRAngleLoc());
1293 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001294}
John McCalle29ba202009-08-20 01:44:21 +00001295
Douglas Gregored9c0f92009-10-29 00:04:11 +00001296/// \brief Instantiate the declaration of a class template partial
1297/// specialization.
1298///
1299/// \param ClassTemplate the (instantiated) class template that is partially
1300// specialized by the instantiation of \p PartialSpec.
1301///
1302/// \param PartialSpec the (uninstantiated) class template partial
1303/// specialization that we are instantiating.
1304///
1305/// \returns true if there was an error, false otherwise.
1306bool
1307TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1308 ClassTemplateDecl *ClassTemplate,
1309 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001310 // Create a local instantiation scope for this class template partial
1311 // specialization, which will contain the instantiations of the template
1312 // parameters.
1313 Sema::LocalInstantiationScope Scope(SemaRef);
1314
Douglas Gregored9c0f92009-10-29 00:04:11 +00001315 // Substitute into the template parameters of the class template partial
1316 // specialization.
1317 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1318 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1319 if (!InstParams)
1320 return true;
1321
1322 // Substitute into the template arguments of the class template partial
1323 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001324 const TemplateArgumentLoc *PartialSpecTemplateArgs
1325 = PartialSpec->getTemplateArgsAsWritten();
1326 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1327
John McCalld5532b62009-11-23 01:53:49 +00001328 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001329 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001330 TemplateArgumentLoc Loc;
1331 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001332 return true;
John McCalld5532b62009-11-23 01:53:49 +00001333 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001334 }
1335
1336
1337 // Check that the template argument list is well-formed for this
1338 // class template.
1339 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1340 InstTemplateArgs.size());
1341 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1342 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001343 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001344 false,
1345 Converted))
1346 return true;
1347
1348 // Figure out where to insert this class template partial specialization
1349 // in the member template's set of class template partial specializations.
1350 llvm::FoldingSetNodeID ID;
1351 ClassTemplatePartialSpecializationDecl::Profile(ID,
1352 Converted.getFlatArguments(),
1353 Converted.flatSize(),
1354 SemaRef.Context);
1355 void *InsertPos = 0;
1356 ClassTemplateSpecializationDecl *PrevDecl
1357 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1358 InsertPos);
1359
1360 // Build the canonical type that describes the converted template
1361 // arguments of the class template partial specialization.
1362 QualType CanonType
1363 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1364 Converted.getFlatArguments(),
1365 Converted.flatSize());
1366
1367 // Build the fully-sugared type for this class template
1368 // specialization as the user wrote in the specialization
1369 // itself. This means that we'll pretty-print the type retrieved
1370 // from the specialization's declaration the way that the user
1371 // actually wrote the specialization, rather than formatting the
1372 // name based on the "canonical" representation used to store the
1373 // template arguments in the specialization.
1374 QualType WrittenTy
1375 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001376 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001377 CanonType);
1378
1379 if (PrevDecl) {
1380 // We've already seen a partial specialization with the same template
1381 // parameters and template arguments. This can happen, for example, when
1382 // substituting the outer template arguments ends up causing two
1383 // class template partial specializations of a member class template
1384 // to have identical forms, e.g.,
1385 //
1386 // template<typename T, typename U>
1387 // struct Outer {
1388 // template<typename X, typename Y> struct Inner;
1389 // template<typename Y> struct Inner<T, Y>;
1390 // template<typename Y> struct Inner<U, Y>;
1391 // };
1392 //
1393 // Outer<int, int> outer; // error: the partial specializations of Inner
1394 // // have the same signature.
1395 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1396 << WrittenTy;
1397 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1398 << SemaRef.Context.getTypeDeclType(PrevDecl);
1399 return true;
1400 }
1401
1402
1403 // Create the class template partial specialization declaration.
1404 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1405 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1406 PartialSpec->getLocation(),
1407 InstParams,
1408 ClassTemplate,
1409 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001410 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001411 0);
1412 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1413 InstPartialSpec->setTypeAsWritten(WrittenTy);
1414
1415 // Add this partial specialization to the set of class template partial
1416 // specializations.
1417 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1418 InsertPos);
1419 return false;
1420}
1421
John McCallce3ff2b2009-08-25 22:02:44 +00001422/// \brief Does substitution on the type of the given function, including
1423/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001424///
John McCallce3ff2b2009-08-25 22:02:44 +00001425/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001426///
1427/// \param Params the instantiated parameter declarations
1428
John McCallce3ff2b2009-08-25 22:02:44 +00001429/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001430/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001431QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001432TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001433 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1434 bool InvalidDecl = false;
1435
John McCallce3ff2b2009-08-25 22:02:44 +00001436 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001437 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001438 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001439 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001440 PEnd = D->param_end();
1441 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001442 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001443 if (PInst->getType()->isVoidType()) {
1444 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1445 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001446 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001447 PInst->getType(),
1448 diag::err_abstract_type_in_decl,
1449 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001450 PInst->setInvalidDecl();
1451
1452 Params.push_back(PInst);
1453 ParamTys.push_back(PInst->getType());
1454
1455 if (PInst->isInvalidDecl())
1456 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001457 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001458 InvalidDecl = true;
1459 }
1460
1461 // FIXME: Deallocate dead declarations.
1462 if (InvalidDecl)
1463 return QualType();
1464
John McCall183700f2009-09-21 23:43:11 +00001465 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001466 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001467 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001468 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1469 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001470 if (ResultType.isNull())
1471 return QualType();
1472
Jay Foadbeaaccd2009-05-21 09:52:38 +00001473 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001474 Proto->isVariadic(), Proto->getTypeQuals(),
1475 D->getLocation(), D->getDeclName());
1476}
1477
Mike Stump1eb44332009-09-09 15:08:12 +00001478/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001479/// declaration (New) from the corresponding fields of its template (Tmpl).
1480///
1481/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001482bool
1483TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001484 FunctionDecl *Tmpl) {
1485 if (Tmpl->isDeleted())
1486 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Douglas Gregorcca9e962009-07-01 22:01:06 +00001488 // If we are performing substituting explicitly-specified template arguments
1489 // or deduced template arguments into a function template and we reach this
1490 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001491 // to keeping the new function template specialization. We therefore
1492 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001493 // into a template instantiation for this specific function template
1494 // specialization, which is not a SFINAE context, so that we diagnose any
1495 // further errors in the declaration itself.
1496 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1497 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1498 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1499 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001500 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001501 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001502 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001503 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001504 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001505 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1506 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001507 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001511 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1512 assert(Proto && "Function template without prototype?");
1513
1514 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1515 Proto->getNoReturnAttr()) {
1516 // The function has an exception specification or a "noreturn"
1517 // attribute. Substitute into each of the exception types.
1518 llvm::SmallVector<QualType, 4> Exceptions;
1519 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1520 // FIXME: Poor location information!
1521 QualType T
1522 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1523 New->getLocation(), New->getDeclName());
1524 if (T.isNull() ||
1525 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1526 continue;
1527
1528 Exceptions.push_back(T);
1529 }
1530
1531 // Rebuild the function type
1532
1533 const FunctionProtoType *NewProto
1534 = New->getType()->getAs<FunctionProtoType>();
1535 assert(NewProto && "Template instantiation without function prototype?");
1536 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1537 NewProto->arg_type_begin(),
1538 NewProto->getNumArgs(),
1539 NewProto->isVariadic(),
1540 NewProto->getTypeQuals(),
1541 Proto->hasExceptionSpec(),
1542 Proto->hasAnyExceptionSpec(),
1543 Exceptions.size(),
1544 Exceptions.data(),
1545 Proto->getNoReturnAttr()));
1546 }
1547
Douglas Gregore53060f2009-06-25 22:08:12 +00001548 return false;
1549}
1550
Douglas Gregor5545e162009-03-24 00:38:23 +00001551/// \brief Initializes common fields of an instantiated method
1552/// declaration (New) from the corresponding fields of its template
1553/// (Tmpl).
1554///
1555/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001556bool
1557TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001558 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001559 if (InitFunctionInstantiation(New, Tmpl))
1560 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Douglas Gregor5545e162009-03-24 00:38:23 +00001562 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1563 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001564 if (Tmpl->isVirtualAsWritten())
1565 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001566
1567 // FIXME: attributes
1568 // FIXME: New needs a pointer to Tmpl
1569 return false;
1570}
Douglas Gregora58861f2009-05-13 20:28:22 +00001571
1572/// \brief Instantiate the definition of the given function from its
1573/// template.
1574///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001575/// \param PointOfInstantiation the point at which the instantiation was
1576/// required. Note that this is not precisely a "point of instantiation"
1577/// for the function, but it's close.
1578///
Douglas Gregora58861f2009-05-13 20:28:22 +00001579/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001580/// function template specialization or member function of a class template
1581/// specialization.
1582///
1583/// \param Recursive if true, recursively instantiates any functions that
1584/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001585///
1586/// \param DefinitionRequired if true, then we are performing an explicit
1587/// instantiation where the body of the function is required. Complain if
1588/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001589void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001590 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001591 bool Recursive,
1592 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001593 if (Function->isInvalidDecl())
1594 return;
1595
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001596 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001598 // Never instantiate an explicit specialization.
1599 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1600 return;
1601
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001602 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001603 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001604 Stmt *Pattern = 0;
1605 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001606 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001607
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001608 if (!Pattern) {
1609 if (DefinitionRequired) {
1610 if (Function->getPrimaryTemplate())
1611 Diag(PointOfInstantiation,
1612 diag::err_explicit_instantiation_undefined_func_template)
1613 << Function->getPrimaryTemplate();
1614 else
1615 Diag(PointOfInstantiation,
1616 diag::err_explicit_instantiation_undefined_member)
1617 << 1 << Function->getDeclName() << Function->getDeclContext();
1618
1619 if (PatternDecl)
1620 Diag(PatternDecl->getLocation(),
1621 diag::note_explicit_instantiation_here);
1622 }
1623
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001624 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001625 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001626
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001627 // C++0x [temp.explicit]p9:
1628 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001629 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001630 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001631 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001632 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001633 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001634 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001636 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1637 if (Inst)
1638 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001639
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001640 // If we're performing recursive template instantiation, create our own
1641 // queue of pending implicit instantiations that we will instantiate later,
1642 // while we're still within our own instantiation context.
1643 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1644 if (Recursive)
1645 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001647 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1648
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001649 // Introduce a new scope where local variable instantiations will be
1650 // recorded.
1651 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001653 // Introduce the instantiated function parameters into the local
1654 // instantiation scope.
1655 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1656 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1657 Function->getParamDecl(I));
1658
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001659 // Enter the scope of this instantiation. We don't use
1660 // PushDeclContext because we don't have a scope.
1661 DeclContext *PreviousContext = CurContext;
1662 CurContext = Function;
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001665 getTemplateInstantiationArgs(Function);
1666
1667 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001668 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001669 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1670 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1671 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001672 }
1673
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001674 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001675 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001676
Douglas Gregor52604ab2009-09-11 21:19:12 +00001677 if (Body.isInvalid())
1678 Function->setInvalidDecl();
1679
Mike Stump1eb44332009-09-09 15:08:12 +00001680 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001681 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001682
1683 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001684
1685 DeclGroupRef DG(Function);
1686 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001688 if (Recursive) {
1689 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001690 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001691 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001693 // Restore the set of pending implicit instantiations.
1694 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1695 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001696}
1697
1698/// \brief Instantiate the definition of the given variable from its
1699/// template.
1700///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001701/// \param PointOfInstantiation the point at which the instantiation was
1702/// required. Note that this is not precisely a "point of instantiation"
1703/// for the function, but it's close.
1704///
1705/// \param Var the already-instantiated declaration of a static member
1706/// variable of a class template specialization.
1707///
1708/// \param Recursive if true, recursively instantiates any functions that
1709/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001710///
1711/// \param DefinitionRequired if true, then we are performing an explicit
1712/// instantiation where an out-of-line definition of the member variable
1713/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001714void Sema::InstantiateStaticDataMemberDefinition(
1715 SourceLocation PointOfInstantiation,
1716 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001717 bool Recursive,
1718 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001719 if (Var->isInvalidDecl())
1720 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Douglas Gregor7caa6822009-07-24 20:34:43 +00001722 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001723 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001724 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001725 assert(Def->isStaticDataMember() && "Not a static data member?");
1726 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Douglas Gregor0d035142009-10-27 18:42:08 +00001728 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001729 // We did not find an out-of-line definition of this static data member,
1730 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001731 // instantiate this definition (or provide a specialization for it) in
1732 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001733 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001734 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001735 Diag(PointOfInstantiation,
1736 diag::err_explicit_instantiation_undefined_member)
1737 << 2 << Var->getDeclName() << Var->getDeclContext();
1738 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1739 }
1740
Douglas Gregor7caa6822009-07-24 20:34:43 +00001741 return;
1742 }
1743
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001744 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001745 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001746 return;
1747
1748 // C++0x [temp.explicit]p9:
1749 // Except for inline functions, other explicit instantiation declarations
1750 // have the effect of suppressing the implicit instantiation of the entity
1751 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001752 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001753 == TSK_ExplicitInstantiationDeclaration)
1754 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Douglas Gregor7caa6822009-07-24 20:34:43 +00001756 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1757 if (Inst)
1758 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Douglas Gregor7caa6822009-07-24 20:34:43 +00001760 // If we're performing recursive template instantiation, create our own
1761 // queue of pending implicit instantiations that we will instantiate later,
1762 // while we're still within our own instantiation context.
1763 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1764 if (Recursive)
1765 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Douglas Gregor7caa6822009-07-24 20:34:43 +00001767 // Enter the scope of this instantiation. We don't use
1768 // PushDeclContext because we don't have a scope.
1769 DeclContext *PreviousContext = CurContext;
1770 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001772 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001773 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001774 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001775 CurContext = PreviousContext;
1776
1777 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001778 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001779 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1780 assert(MSInfo && "Missing member specialization information?");
1781 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1782 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001783 DeclGroupRef DG(Var);
1784 Consumer.HandleTopLevelDecl(DG);
1785 }
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor7caa6822009-07-24 20:34:43 +00001787 if (Recursive) {
1788 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001789 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001790 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregor7caa6822009-07-24 20:34:43 +00001792 // Restore the set of pending implicit instantiations.
1793 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001794 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001795}
Douglas Gregor815215d2009-05-27 05:35:12 +00001796
Anders Carlsson09025312009-08-29 05:16:22 +00001797void
1798Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1799 const CXXConstructorDecl *Tmpl,
1800 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Anders Carlsson09025312009-08-29 05:16:22 +00001802 llvm::SmallVector<MemInitTy*, 4> NewInits;
1803
1804 // Instantiate all the initializers.
1805 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001806 InitsEnd = Tmpl->init_end();
1807 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001808 CXXBaseOrMemberInitializer *Init = *Inits;
1809
1810 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson09025312009-08-29 05:16:22 +00001812 // Instantiate all the arguments.
1813 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1814 Args != ArgsEnd; ++Args) {
1815 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1816
1817 if (NewArg.isInvalid())
1818 New->setInvalidDecl();
1819 else
1820 NewArgs.push_back(NewArg.takeAs<Expr>());
1821 }
1822
1823 MemInitResult NewInit;
1824
1825 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001826 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001827 TemplateArgs,
1828 Init->getSourceLocation(),
1829 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001830 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001831 New->setInvalidDecl();
1832 continue;
1833 }
1834
John McCalla93c9342009-12-07 02:54:59 +00001835 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001836 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001837 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001838 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001839 Init->getRParenLoc(),
1840 New->getParent());
1841 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001842 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001844 // Is this an anonymous union?
1845 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001846 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001847 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001848 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1849 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001850
1851 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001852 NewArgs.size(),
1853 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001854 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001855 Init->getRParenLoc());
1856 }
1857
1858 if (NewInit.isInvalid())
1859 New->setInvalidDecl();
1860 else {
1861 // FIXME: It would be nice if ASTOwningVector had a release function.
1862 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Anders Carlsson09025312009-08-29 05:16:22 +00001864 NewInits.push_back((MemInitTy *)NewInit.get());
1865 }
1866 }
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Anders Carlsson09025312009-08-29 05:16:22 +00001868 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001870 /*FIXME: ColonLoc */
1871 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001872 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001873}
1874
John McCall52a575a2009-08-29 08:11:13 +00001875// TODO: this could be templated if the various decl types used the
1876// same method name.
1877static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1878 ClassTemplateDecl *Instance) {
1879 Pattern = Pattern->getCanonicalDecl();
1880
1881 do {
1882 Instance = Instance->getCanonicalDecl();
1883 if (Pattern == Instance) return true;
1884 Instance = Instance->getInstantiatedFromMemberTemplate();
1885 } while (Instance);
1886
1887 return false;
1888}
1889
Douglas Gregor0d696532009-09-28 06:34:35 +00001890static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1891 FunctionTemplateDecl *Instance) {
1892 Pattern = Pattern->getCanonicalDecl();
1893
1894 do {
1895 Instance = Instance->getCanonicalDecl();
1896 if (Pattern == Instance) return true;
1897 Instance = Instance->getInstantiatedFromMemberTemplate();
1898 } while (Instance);
1899
1900 return false;
1901}
1902
Douglas Gregored9c0f92009-10-29 00:04:11 +00001903static bool
1904isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1905 ClassTemplatePartialSpecializationDecl *Instance) {
1906 Pattern
1907 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1908 do {
1909 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1910 Instance->getCanonicalDecl());
1911 if (Pattern == Instance)
1912 return true;
1913 Instance = Instance->getInstantiatedFromMember();
1914 } while (Instance);
1915
1916 return false;
1917}
1918
John McCall52a575a2009-08-29 08:11:13 +00001919static bool isInstantiationOf(CXXRecordDecl *Pattern,
1920 CXXRecordDecl *Instance) {
1921 Pattern = Pattern->getCanonicalDecl();
1922
1923 do {
1924 Instance = Instance->getCanonicalDecl();
1925 if (Pattern == Instance) return true;
1926 Instance = Instance->getInstantiatedFromMemberClass();
1927 } while (Instance);
1928
1929 return false;
1930}
1931
1932static bool isInstantiationOf(FunctionDecl *Pattern,
1933 FunctionDecl *Instance) {
1934 Pattern = Pattern->getCanonicalDecl();
1935
1936 do {
1937 Instance = Instance->getCanonicalDecl();
1938 if (Pattern == Instance) return true;
1939 Instance = Instance->getInstantiatedFromMemberFunction();
1940 } while (Instance);
1941
1942 return false;
1943}
1944
1945static bool isInstantiationOf(EnumDecl *Pattern,
1946 EnumDecl *Instance) {
1947 Pattern = Pattern->getCanonicalDecl();
1948
1949 do {
1950 Instance = Instance->getCanonicalDecl();
1951 if (Pattern == Instance) return true;
1952 Instance = Instance->getInstantiatedFromMemberEnum();
1953 } while (Instance);
1954
1955 return false;
1956}
1957
John McCalled976492009-12-04 22:46:56 +00001958static bool isInstantiationOf(UsingShadowDecl *Pattern,
1959 UsingShadowDecl *Instance,
1960 ASTContext &C) {
1961 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1962}
1963
1964static bool isInstantiationOf(UsingDecl *Pattern,
1965 UsingDecl *Instance,
1966 ASTContext &C) {
1967 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1968}
1969
John McCall7ba107a2009-11-18 02:36:19 +00001970static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1971 UsingDecl *Instance,
1972 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001973 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001974}
1975
1976static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001977 UsingDecl *Instance,
1978 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001979 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001980}
1981
John McCall52a575a2009-08-29 08:11:13 +00001982static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1983 VarDecl *Instance) {
1984 assert(Instance->isStaticDataMember());
1985
1986 Pattern = Pattern->getCanonicalDecl();
1987
1988 do {
1989 Instance = Instance->getCanonicalDecl();
1990 if (Pattern == Instance) return true;
1991 Instance = Instance->getInstantiatedFromStaticDataMember();
1992 } while (Instance);
1993
1994 return false;
1995}
1996
John McCalled976492009-12-04 22:46:56 +00001997// Other is the prospective instantiation
1998// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001999static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002000 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002001 if (UnresolvedUsingTypenameDecl *UUD
2002 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2003 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2004 return isInstantiationOf(UUD, UD, Ctx);
2005 }
2006 }
2007
2008 if (UnresolvedUsingValueDecl *UUD
2009 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002010 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2011 return isInstantiationOf(UUD, UD, Ctx);
2012 }
2013 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002014
Anders Carlsson0d8df782009-08-29 19:37:28 +00002015 return false;
2016 }
Mike Stump1eb44332009-09-09 15:08:12 +00002017
John McCall52a575a2009-08-29 08:11:13 +00002018 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2019 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
John McCall52a575a2009-08-29 08:11:13 +00002021 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2022 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002023
John McCall52a575a2009-08-29 08:11:13 +00002024 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2025 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002026
Douglas Gregor7caa6822009-07-24 20:34:43 +00002027 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002028 if (Var->isStaticDataMember())
2029 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2030
2031 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2032 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002033
Douglas Gregor0d696532009-09-28 06:34:35 +00002034 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2035 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2036
Douglas Gregored9c0f92009-10-29 00:04:11 +00002037 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2038 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2039 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2040 PartialSpec);
2041
Anders Carlssond8b285f2009-09-01 04:26:58 +00002042 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2043 if (!Field->getDeclName()) {
2044 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002045 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002046 cast<FieldDecl>(D);
2047 }
2048 }
Mike Stump1eb44332009-09-09 15:08:12 +00002049
John McCalled976492009-12-04 22:46:56 +00002050 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2051 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2052
2053 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2054 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2055
Douglas Gregor815215d2009-05-27 05:35:12 +00002056 return D->getDeclName() && isa<NamedDecl>(Other) &&
2057 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2058}
2059
2060template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002061static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002062 NamedDecl *D,
2063 ForwardIterator first,
2064 ForwardIterator last) {
2065 for (; first != last; ++first)
2066 if (isInstantiationOf(Ctx, D, *first))
2067 return cast<NamedDecl>(*first);
2068
2069 return 0;
2070}
2071
John McCall02cace72009-08-28 07:59:38 +00002072/// \brief Finds the instantiation of the given declaration context
2073/// within the current instantiation.
2074///
2075/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002076DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2077 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002078 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002079 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002080 return cast_or_null<DeclContext>(ID);
2081 } else return DC;
2082}
2083
Douglas Gregored961e72009-05-27 17:54:46 +00002084/// \brief Find the instantiation of the given declaration within the
2085/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002086///
2087/// This routine is intended to be used when \p D is a declaration
2088/// referenced from within a template, that needs to mapped into the
2089/// corresponding declaration within an instantiation. For example,
2090/// given:
2091///
2092/// \code
2093/// template<typename T>
2094/// struct X {
2095/// enum Kind {
2096/// KnownValue = sizeof(T)
2097/// };
2098///
2099/// bool getKind() const { return KnownValue; }
2100/// };
2101///
2102/// template struct X<int>;
2103/// \endcode
2104///
2105/// In the instantiation of X<int>::getKind(), we need to map the
2106/// EnumConstantDecl for KnownValue (which refers to
2107/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002108/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2109/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002110NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2111 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002112 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002113 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2114 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2115 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002116 // D is a local of some kind. Look into the map of local
2117 // declarations to their instantiations.
2118 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2119 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002120
Douglas Gregore95b4092009-09-16 18:34:49 +00002121 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2122 if (!Record->isDependentContext())
2123 return D;
2124
2125 // If the RecordDecl is actually the injected-class-name or a "templated"
2126 // declaration for a class template or class template partial
2127 // specialization, substitute into the injected-class-name of the
2128 // class template or partial specialization to find the new DeclContext.
2129 QualType T;
2130 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2131
2132 if (ClassTemplate) {
2133 T = ClassTemplate->getInjectedClassNameType(Context);
2134 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2135 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2136 T = Context.getTypeDeclType(Record);
2137 ClassTemplate = PartialSpec->getSpecializedTemplate();
2138 }
2139
2140 if (!T.isNull()) {
2141 // Substitute into the injected-class-name to get the type corresponding
2142 // to the instantiation we want. This substitution should never fail,
2143 // since we know we can instantiate the injected-class-name or we wouldn't
2144 // have gotten to the injected-class-name!
2145 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2146 // instantiation in the common case?
2147 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2148 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2149
2150 if (!T->isDependentType()) {
2151 assert(T->isRecordType() && "Instantiation must produce a record type");
2152 return T->getAs<RecordType>()->getDecl();
2153 }
2154
2155 // We are performing "partial" template instantiation to create the
2156 // member declarations for the members of a class template
2157 // specialization. Therefore, D is actually referring to something in
2158 // the current instantiation. Look through the current context,
2159 // which contains actual instantiations, to find the instantiation of
2160 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002161 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002162 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002163 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002164 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002165 if (isInstantiationOf(ClassTemplate,
2166 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002167 return Spec;
2168 }
2169
Mike Stump1eb44332009-09-09 15:08:12 +00002170 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002171 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002172 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002173 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002174
2175 // Fall through to deal with other dependent record types (e.g.,
2176 // anonymous unions in class templates).
2177 }
John McCall52a575a2009-08-29 08:11:13 +00002178
Douglas Gregore95b4092009-09-16 18:34:49 +00002179 if (!ParentDC->isDependentContext())
2180 return D;
2181
2182 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002183 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002184 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Douglas Gregor815215d2009-05-27 05:35:12 +00002186 if (ParentDC != D->getDeclContext()) {
2187 // We performed some kind of instantiation in the parent context,
2188 // so now we need to look into the instantiated parent context to
2189 // find the instantiation of the declaration D.
2190 NamedDecl *Result = 0;
2191 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002192 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002193 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2194 } else {
2195 // Since we don't have a name for the entity we're looking for,
2196 // our only option is to walk through all of the declarations to
2197 // find that name. This will occur in a few cases:
2198 //
2199 // - anonymous struct/union within a template
2200 // - unnamed class/struct/union/enum within a template
2201 //
2202 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002203 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002204 ParentDC->decls_begin(),
2205 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002206 }
Mike Stump1eb44332009-09-09 15:08:12 +00002207
John McCall9f54ad42009-12-10 09:41:52 +00002208 // UsingShadowDecls can instantiate to nothing because of using hiding.
2209 assert((Result || isa<UsingShadowDecl>(D))
2210 && "Unable to find instantiation of declaration!");
2211
Douglas Gregor815215d2009-05-27 05:35:12 +00002212 D = Result;
2213 }
2214
Douglas Gregor815215d2009-05-27 05:35:12 +00002215 return D;
2216}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002217
Mike Stump1eb44332009-09-09 15:08:12 +00002218/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002219/// instantiations we have seen until this point.
2220void Sema::PerformPendingImplicitInstantiations() {
2221 while (!PendingImplicitInstantiations.empty()) {
2222 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002223 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Douglas Gregor7caa6822009-07-24 20:34:43 +00002225 // Instantiate function definitions
2226 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002227 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002228 Function->getLocation(), *this,
2229 Context.getSourceManager(),
2230 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002232 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002233 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002234 continue;
2235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Douglas Gregor7caa6822009-07-24 20:34:43 +00002237 // Instantiate static data member definitions.
2238 VarDecl *Var = cast<VarDecl>(Inst.first);
2239 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002240
Mike Stump1eb44332009-09-09 15:08:12 +00002241 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002242 Var->getLocation(), *this,
2243 Context.getSourceManager(),
2244 "instantiating static data member "
2245 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Douglas Gregor7caa6822009-07-24 20:34:43 +00002247 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002248 }
2249}