blob: 1ec91bd55ec36bcd017e9444db546d6e624b6a82 [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
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000148 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000150 return Typedef;
151}
152
Douglas Gregor6eef5192009-12-14 19:27:10 +0000153/// \brief Instantiate the arguments provided as part of initialization.
154///
155/// \returns true if an error occurred, false otherwise.
156static bool InstantiateInitializationArguments(Sema &SemaRef,
157 Expr **Args, unsigned NumArgs,
158 const MultiLevelTemplateArgumentList &TemplateArgs,
159 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
160 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
161 for (unsigned I = 0; I != NumArgs; ++I) {
162 // When we hit the first defaulted argument, break out of the loop:
163 // we don't pass those default arguments on.
164 if (Args[I]->isDefaultArgument())
165 break;
166
167 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
168 if (Arg.isInvalid())
169 return true;
170
171 Expr *ArgExpr = (Expr *)Arg.get();
172 InitArgs.push_back(Arg.release());
173
174 // FIXME: We're faking all of the comma locations. Do we need them?
175 FakeCommaLocs.push_back(
176 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
177 }
178
179 return false;
180}
181
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000182Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000183 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000184 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000185 TemplateArgs,
186 D->getTypeSpecStartLoc(),
187 D->getDeclName());
188 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000189 return 0;
190
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000191 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000192 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
193 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000194 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000195 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 Var->setThreadSpecified(D->isThreadSpecified());
197 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
198 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000199
200 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000201 // out-of-line, the instantiation will have the same lexical
202 // context (which will be a namespace scope) as the template.
203 if (D->isOutOfLine())
204 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Mike Stump390b4cc2009-05-16 07:39:55 +0000206 // FIXME: In theory, we could have a previous declaration for variables that
207 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000208 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000209 // FIXME: having to fake up a LookupResult is dumb.
210 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
211 Sema::LookupOrdinaryName);
212 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Douglas Gregor7caa6822009-07-24 20:34:43 +0000214 if (D->isOutOfLine()) {
215 D->getLexicalDeclContext()->addDecl(Var);
216 Owner->makeDeclVisibleInContext(Var);
217 } else {
218 Owner->addDecl(Var);
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000221 // Link instantiations of static data members back to the template from
222 // which they were instantiated.
223 if (Var->isStaticDataMember())
224 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000225 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000226
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000227 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000228 if (Var->isStaticDataMember() && !D->isOutOfLine())
229 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
230 else
231 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
232
Douglas Gregor6eef5192009-12-14 19:27:10 +0000233 // Extract the initializer, skipping through any temporary-binding
234 // expressions and look at the subexpression as it was written.
235 Expr *DInit = D->getInit();
236 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
237 DInit = Binder->getSubExpr();
238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
239 DInit = ICE->getSubExprAsWritten();
240
241 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
242 // The initializer is a parenthesized list of expressions that is
243 // type-dependent. Instantiate each of the expressions; we'll be
244 // performing direct initialization with them.
245 llvm::SmallVector<SourceLocation, 4> CommaLocs;
246 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
247 if (!InstantiateInitializationArguments(SemaRef,
248 PLE->getExprs(),
249 PLE->getNumExprs(),
250 TemplateArgs,
251 CommaLocs, InitArgs)) {
252 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000253 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000254 PLE->getLParenLoc(),
255 move_arg(InitArgs),
256 CommaLocs.data(),
257 PLE->getRParenLoc());
258 }
259 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
260 // The initializer resolved to a constructor. Instantiate the constructor
261 // arguments.
262 llvm::SmallVector<SourceLocation, 4> CommaLocs;
263 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
264
265 if (!InstantiateInitializationArguments(SemaRef,
266 Construct->getArgs(),
267 Construct->getNumArgs(),
268 TemplateArgs,
269 CommaLocs, InitArgs)) {
270 if (D->hasCXXDirectInitializer()) {
271 SourceLocation FakeLParenLoc =
272 SemaRef.PP.getLocForEndOfToken(D->getLocation());
273 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
274 : CommaLocs.back();
275 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
276 FakeLParenLoc,
277 move_arg(InitArgs),
278 CommaLocs.data(),
279 FakeRParenLoc);
280 } else if (InitArgs.size() == 1) {
281 Expr *Init = (Expr*)(InitArgs.take()[0]);
282 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
283 SemaRef.Owned(Init),
284 false);
285 } else {
286 assert(InitArgs.size() == 0);
287 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
288 }
289 }
290 } else {
291 OwningExprResult Init
292 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
293
294 // FIXME: Not happy about invalidating decls just because of a bad
295 // initializer, unless it affects the type.
296 if (Init.isInvalid())
297 Var->setInvalidDecl();
298 else
299 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
300 D->hasCXXDirectInitializer());
301 }
302
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000303 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000304 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
305 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000306
307 return Var;
308}
309
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
311 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000312 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000313 if (DI->getType()->isDependentType()) {
314 DI = SemaRef.SubstType(DI, TemplateArgs,
315 D->getLocation(), D->getDeclName());
316 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000317 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000318 Invalid = true;
319 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000320 // C++ [temp.arg.type]p3:
321 // If a declaration acquires a function type through a type
322 // dependent on a template-parameter and this causes a
323 // declaration that does not use the syntactic form of a
324 // function declarator to have function type, the program is
325 // ill-formed.
326 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000327 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 Invalid = true;
329 }
330 }
331
332 Expr *BitWidth = D->getBitWidth();
333 if (Invalid)
334 BitWidth = 0;
335 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 // The bit-width expression is not potentially evaluated.
337 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000339 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000340 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000341 if (InstantiatedBitWidth.isInvalid()) {
342 Invalid = true;
343 BitWidth = 0;
344 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000345 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000346 }
347
John McCall07fb6be2009-10-22 23:33:21 +0000348 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
349 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351 D->getLocation(),
352 D->isMutable(),
353 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000354 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355 D->getAccess(),
356 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000357 if (!Field) {
358 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000359 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000362 InstantiateAttrs(D, Field);
363
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000364 if (Invalid)
365 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000367 if (!Field->getDeclName()) {
368 // Keep track of where this decl came from.
369 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 Field->setImplicit(D->isImplicit());
373 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000374
375 return Field;
376}
377
John McCall02cace72009-08-28 07:59:38 +0000378Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
379 FriendDecl::FriendUnion FU;
380
381 // Handle friend type expressions by simply substituting template
382 // parameters into the pattern type.
383 if (Type *Ty = D->getFriendType()) {
384 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
385 D->getLocation(), DeclarationName());
386 if (T.isNull()) return 0;
387
388 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
389 FU = T.getTypePtr();
390
391 // Handle everything else by appropriate substitution.
392 } else {
393 NamedDecl *ND = D->getFriendDecl();
394 assert(ND && "friend decl must be a decl or a type!");
395
Douglas Gregora735b202009-10-13 14:39:41 +0000396 // FIXME: We have a problem here, because the nested call to Visit(ND)
397 // will inject the thing that the friend references into the current
398 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000399 Decl *NewND;
400
401 // Hack to make this work almost well pending a rewrite.
402 if (ND->getDeclContext()->isRecord())
403 NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs);
Douglas Gregor7557a132009-12-24 20:56:24 +0000404 else if (D->wasSpecialization()) {
405 // Totally egregious hack to work around PR5866
406 return 0;
407 } else
John McCalle129d442009-12-17 23:21:11 +0000408 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000409 if (!NewND) return 0;
410
411 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
John McCall02cace72009-08-28 07:59:38 +0000414 FriendDecl *FD =
415 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
416 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000417 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000418 Owner->addDecl(FD);
419 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000420}
421
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
423 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregorac7610d2009-06-22 20:57:11 +0000425 // The expression in a static assertion is not potentially evaluated.
426 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000428 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000429 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 if (InstantiatedAssertExpr.isInvalid())
431 return 0;
432
Douglas Gregor43d9d922009-08-08 01:41:12 +0000433 OwningExprResult Message(SemaRef, D->getMessage());
434 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000435 Decl *StaticAssert
436 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000437 move(InstantiatedAssertExpr),
438 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000439 return StaticAssert;
440}
441
442Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000443 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000445 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000446 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000447 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000448 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000449 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 Enum->startDefinition();
451
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000452 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453
454 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000455 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
456 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000457 EC != ECEnd; ++EC) {
458 // The specified value for the enumerator.
459 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000460 if (Expr *UninstValue = EC->getInitExpr()) {
461 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000462 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000463 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
John McCallce3ff2b2009-08-25 22:02:44 +0000465 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000466 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000467
468 // Drop the initial value and continue.
469 bool isInvalid = false;
470 if (Value.isInvalid()) {
471 Value = SemaRef.Owned((Expr *)0);
472 isInvalid = true;
473 }
474
Mike Stump1eb44332009-09-09 15:08:12 +0000475 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000476 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
477 EC->getLocation(), EC->getIdentifier(),
478 move(Value));
479
480 if (isInvalid) {
481 if (EnumConst)
482 EnumConst->setInvalidDecl();
483 Enum->setInvalidDecl();
484 }
485
486 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000487 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000488 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000489 LastEnumConst = EnumConst;
490 }
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000493 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000494 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000495 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
496 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000497 &Enumerators[0], Enumerators.size(),
498 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000499
500 return Enum;
501}
502
Douglas Gregor6477b692009-03-25 15:04:13 +0000503Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
504 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
505 return 0;
506}
507
Douglas Gregored9c0f92009-10-29 00:04:11 +0000508namespace {
509 class SortDeclByLocation {
510 SourceManager &SourceMgr;
511
512 public:
513 explicit SortDeclByLocation(SourceManager &SourceMgr)
514 : SourceMgr(SourceMgr) { }
515
516 bool operator()(const Decl *X, const Decl *Y) const {
517 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
518 Y->getLocation());
519 }
520 };
521}
522
John McCalle29ba202009-08-20 01:44:21 +0000523Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000524 // Create a local instantiation scope for this class template, which
525 // will contain the instantiations of the template parameters.
526 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000527 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000528 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000529 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000530 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000531
532 CXXRecordDecl *Pattern = D->getTemplatedDecl();
533 CXXRecordDecl *RecordInst
534 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
535 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000536 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
537 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000538
539 ClassTemplateDecl *Inst
540 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
541 D->getIdentifier(), InstParams, RecordInst, 0);
542 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000543 if (D->getFriendObjectKind())
544 Inst->setObjectOfFriendDecl(true);
545 else
546 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000547 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000548
549 // Trigger creation of the type for the instantiation.
550 SemaRef.Context.getTypeDeclType(RecordInst);
551
Douglas Gregor259571e2009-10-30 22:42:42 +0000552 // Finish handling of friends.
553 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000554 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000555 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000556
John McCalle29ba202009-08-20 01:44:21 +0000557 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000558
559 // First, we sort the partial specializations by location, so
560 // that we instantiate them in the order they were declared.
561 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
562 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
563 P = D->getPartialSpecializations().begin(),
564 PEnd = D->getPartialSpecializations().end();
565 P != PEnd; ++P)
566 PartialSpecs.push_back(&*P);
567 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
568 SortDeclByLocation(SemaRef.SourceMgr));
569
570 // Instantiate all of the partial specializations of this member class
571 // template.
572 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
573 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
574
John McCalle29ba202009-08-20 01:44:21 +0000575 return Inst;
576}
577
Douglas Gregord60e1052009-08-27 16:57:43 +0000578Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000579TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
580 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000581 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
582
583 // Lookup the already-instantiated declaration in the instantiation
584 // of the class template and return that.
585 DeclContext::lookup_result Found
586 = Owner->lookup(ClassTemplate->getDeclName());
587 if (Found.first == Found.second)
588 return 0;
589
590 ClassTemplateDecl *InstClassTemplate
591 = dyn_cast<ClassTemplateDecl>(*Found.first);
592 if (!InstClassTemplate)
593 return 0;
594
595 Decl *DCanon = D->getCanonicalDecl();
596 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
597 P = InstClassTemplate->getPartialSpecializations().begin(),
598 PEnd = InstClassTemplate->getPartialSpecializations().end();
599 P != PEnd; ++P) {
600 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
601 return &*P;
602 }
603
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000604 return 0;
605}
606
607Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000608TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000609 // Create a local instantiation scope for this function template, which
610 // will contain the instantiations of the template parameters and then get
611 // merged with the local instantiation scope for the function template
612 // itself.
613 Sema::LocalInstantiationScope Scope(SemaRef);
614
Douglas Gregord60e1052009-08-27 16:57:43 +0000615 TemplateParameterList *TempParams = D->getTemplateParameters();
616 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000617 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000618 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000619
Douglas Gregora735b202009-10-13 14:39:41 +0000620 FunctionDecl *Instantiated = 0;
621 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
622 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
623 InstParams));
624 else
625 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
626 D->getTemplatedDecl(),
627 InstParams));
628
629 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000630 return 0;
631
Mike Stump1eb44332009-09-09 15:08:12 +0000632 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000633 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000634 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000635 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000636 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000637 assert(InstTemplate &&
638 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000639
640 // Link the instantiation back to the pattern *unless* this is a
641 // non-definition friend declaration.
642 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
643 !(InstTemplate->getFriendObjectKind() &&
644 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000645 InstTemplate->setInstantiatedFromMemberTemplate(D);
646
647 // Add non-friends into the owner.
648 if (!InstTemplate->getFriendObjectKind())
649 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000650 return InstTemplate;
651}
652
Douglas Gregord475b8d2009-03-25 21:17:03 +0000653Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
654 CXXRecordDecl *PrevDecl = 0;
655 if (D->isInjectedClassName())
656 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000657 else if (D->getPreviousDeclaration()) {
658 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
659 TemplateArgs);
660 if (!Prev) return 0;
661 PrevDecl = cast<CXXRecordDecl>(Prev);
662 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000663
664 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000665 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000666 D->getLocation(), D->getIdentifier(),
667 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000668 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000669 // FIXME: Check against AS_none is an ugly hack to work around the issue that
670 // the tag decls introduced by friend class declarations don't have an access
671 // specifier. Remove once this area of the code gets sorted out.
672 if (D->getAccess() != AS_none)
673 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000674 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000675 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000676
John McCall02cace72009-08-28 07:59:38 +0000677 // If the original function was part of a friend declaration,
678 // inherit its namespace state.
679 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
680 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
681
Anders Carlssond8b285f2009-09-01 04:26:58 +0000682 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
683
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000684 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000685 return Record;
686}
687
John McCall02cace72009-08-28 07:59:38 +0000688/// Normal class members are of more specific types and therefore
689/// don't make it here. This function serves two purposes:
690/// 1) instantiating function templates
691/// 2) substituting friend declarations
692/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000693Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000694 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000695 // Check whether there is already a function template specialization for
696 // this declaration.
697 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
698 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000699 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000700 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000701 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000702 TemplateArgs.getInnermost().getFlatArgumentList(),
703 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000704 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
706 FunctionTemplateSpecializationInfo *Info
707 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000708 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Douglas Gregor127102b2009-06-29 20:59:39 +0000710 // If we already have a function template specialization, return it.
711 if (Info)
712 return Info->Function;
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Douglas Gregor550d9b22009-10-31 17:21:17 +0000715 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Douglas Gregore53060f2009-06-25 22:08:12 +0000717 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000718 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000719 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000720 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000721
Douglas Gregore53060f2009-06-25 22:08:12 +0000722 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000723 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
724 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000725 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000726 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000727 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000728 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000729 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000730 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Douglas Gregore53060f2009-06-25 22:08:12 +0000732 // Attach the parameters
733 for (unsigned P = 0; P < Params.size(); ++P)
734 Params[P]->setOwningFunction(Function);
735 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000736
Douglas Gregora735b202009-10-13 14:39:41 +0000737 if (TemplateParams) {
738 // Our resulting instantiation is actually a function template, since we
739 // are substituting only the outer template parameters. For example, given
740 //
741 // template<typename T>
742 // struct X {
743 // template<typename U> friend void f(T, U);
744 // };
745 //
746 // X<int> x;
747 //
748 // We are instantiating the friend function template "f" within X<int>,
749 // which means substituting int for T, but leaving "f" as a friend function
750 // template.
751 // Build the function template itself.
752 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
753 Function->getLocation(),
754 Function->getDeclName(),
755 TemplateParams, Function);
756 Function->setDescribedFunctionTemplate(FunctionTemplate);
757 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000758 } else if (FunctionTemplate) {
759 // Record this function template specialization.
760 Function->setFunctionTemplateSpecialization(SemaRef.Context,
761 FunctionTemplate,
762 &TemplateArgs.getInnermost(),
763 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000764 }
Douglas Gregora735b202009-10-13 14:39:41 +0000765
Douglas Gregore53060f2009-06-25 22:08:12 +0000766 if (InitFunctionInstantiation(Function, D))
767 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Douglas Gregore53060f2009-06-25 22:08:12 +0000769 bool Redeclaration = false;
770 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000771
John McCall68263142009-11-18 22:49:29 +0000772 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
773 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
774
Douglas Gregora735b202009-10-13 14:39:41 +0000775 if (TemplateParams || !FunctionTemplate) {
776 // Look only into the namespace where the friend would be declared to
777 // find a previous declaration. This is the innermost enclosing namespace,
778 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000779 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000780
Douglas Gregora735b202009-10-13 14:39:41 +0000781 // In C++, the previous declaration we find might be a tag type
782 // (class or enum). In this case, the new declaration will hide the
783 // tag type. Note that this does does not apply if we're declaring a
784 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000785 if (Previous.isSingleTagDecl())
786 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000787 }
788
John McCall9f54ad42009-12-10 09:41:52 +0000789 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
790 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000791 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000792
Douglas Gregora735b202009-10-13 14:39:41 +0000793 // If the original function was part of a friend declaration,
794 // inherit its namespace state and add it to the owner.
795 NamedDecl *FromFriendD
796 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
797 if (FromFriendD->getFriendObjectKind()) {
798 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000799 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000800 if (TemplateParams) {
801 ToFriendD = cast<NamedDecl>(FunctionTemplate);
802 PrevDecl = FunctionTemplate->getPreviousDeclaration();
803 } else {
804 ToFriendD = Function;
805 PrevDecl = Function->getPreviousDeclaration();
806 }
807 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
808 if (!Owner->isDependentContext() && !PrevDecl)
809 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
810
811 if (!TemplateParams)
812 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
813 }
814
Douglas Gregore53060f2009-06-25 22:08:12 +0000815 return Function;
816}
817
Douglas Gregord60e1052009-08-27 16:57:43 +0000818Decl *
819TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
820 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000821 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
822 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000823 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000824 // We are creating a function template specialization from a function
825 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000826 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000827 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000828 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000829 TemplateArgs.getInnermost().getFlatArgumentList(),
830 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000831 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000832
833 FunctionTemplateSpecializationInfo *Info
834 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000835 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Douglas Gregor6b906862009-08-21 00:16:32 +0000837 // If we already have a function template specialization, return it.
838 if (Info)
839 return Info->Function;
840 }
841
Douglas Gregor550d9b22009-10-31 17:21:17 +0000842 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000843
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000844 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000845 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000846 if (T.isNull())
847 return 0;
848
849 // Build the instantiated method declaration.
850 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000851 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregordec06662009-08-21 18:42:58 +0000853 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000855 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
856 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
857 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000858 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
859 Constructor->getLocation(),
860 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000861 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000862 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000863 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000864 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
865 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
866 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
867 SemaRef.Context.getCanonicalType(ClassTy));
868 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
869 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000870 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000871 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000872 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000873 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000874 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000875 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
876 ConvTy);
877 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
878 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000879 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000880 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000881 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000882 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000883 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000884 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000885 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000886 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000887
Douglas Gregord60e1052009-08-27 16:57:43 +0000888 if (TemplateParams) {
889 // Our resulting instantiation is actually a function template, since we
890 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000891 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000892 // template<typename T>
893 // struct X {
894 // template<typename U> void f(T, U);
895 // };
896 //
897 // X<int> x;
898 //
899 // We are instantiating the member template "f" within X<int>, which means
900 // substituting int for T, but leaving "f" as a member function template.
901 // Build the function template itself.
902 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
903 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000904 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000905 TemplateParams, Method);
906 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000907 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000908 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000909 } else if (FunctionTemplate) {
910 // Record this function template specialization.
911 Method->setFunctionTemplateSpecialization(SemaRef.Context,
912 FunctionTemplate,
913 &TemplateArgs.getInnermost(),
914 InsertPos);
915 } else {
916 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000917 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000918 }
919
Mike Stump1eb44332009-09-09 15:08:12 +0000920 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000921 // out-of-line, the instantiation will have the same lexical
922 // context (which will be a namespace scope) as the template.
923 if (D->isOutOfLine())
924 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Douglas Gregor5545e162009-03-24 00:38:23 +0000926 // Attach the parameters
927 for (unsigned P = 0; P < Params.size(); ++P)
928 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000929 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000930
931 if (InitMethodInstantiation(Method, D))
932 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000933
John McCall68263142009-11-18 22:49:29 +0000934 LookupResult Previous(SemaRef, Name, SourceLocation(),
935 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregord60e1052009-08-27 16:57:43 +0000937 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000938 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregordec06662009-08-21 18:42:58 +0000940 // In C++, the previous declaration we find might be a tag type
941 // (class or enum). In this case, the new declaration will hide the
942 // tag type. Note that this does does not apply if we're declaring a
943 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000944 if (Previous.isSingleTagDecl())
945 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000946 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000947
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000948 bool Redeclaration = false;
949 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000950 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000951 /*FIXME:*/OverloadableAttrRequired);
952
Douglas Gregor4ba31362009-12-01 17:24:26 +0000953 if (D->isPure())
954 SemaRef.CheckPureMethod(Method, SourceRange());
955
John McCall68263142009-11-18 22:49:29 +0000956 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000957 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000958 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000960 return Method;
961}
962
Douglas Gregor615c5d42009-03-24 16:43:20 +0000963Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000964 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000965}
966
Douglas Gregor03b2b072009-03-24 00:15:49 +0000967Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000968 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000969}
970
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000971Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000972 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000973}
974
Douglas Gregor6477b692009-03-25 15:04:13 +0000975ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000976 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000977 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000978 if (DI) {
979 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
980 D->getDeclName());
981 if (DI) T = DI->getType();
982 } else {
983 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
984 D->getDeclName());
985 DI = 0;
986 }
987
988 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000989 return 0;
990
John McCall58e46772009-10-23 21:48:59 +0000991 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000992
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000993 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000994 ParmVarDecl *Param
995 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
996 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000997
Anders Carlsson9351c172009-08-25 03:18:48 +0000998 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000999 if (D->hasUninstantiatedDefaultArg())
1000 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001001 else if (Expr *Arg = D->getDefaultArg())
1002 Param->setUninstantiatedDefaultArg(Arg);
1003
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001004 // Note: we don't try to instantiate function parameters until after
1005 // we've instantiated the function's type. Therefore, we don't have
1006 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001007 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001008 return Param;
1009}
1010
John McCalle29ba202009-08-20 01:44:21 +00001011Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1012 TemplateTypeParmDecl *D) {
1013 // TODO: don't always clone when decls are refcounted.
1014 const Type* T = D->getTypeForDecl();
1015 assert(T->isTemplateTypeParmType());
1016 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001017
John McCalle29ba202009-08-20 01:44:21 +00001018 TemplateTypeParmDecl *Inst =
1019 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001020 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001021 TTPT->getName(),
1022 D->wasDeclaredWithTypename(),
1023 D->isParameterPack());
1024
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001025 if (D->hasDefaultArgument())
1026 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001027
Douglas Gregor550d9b22009-10-31 17:21:17 +00001028 // Introduce this template parameter's instantiation into the instantiation
1029 // scope.
1030 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1031
John McCalle29ba202009-08-20 01:44:21 +00001032 return Inst;
1033}
1034
Douglas Gregor33642df2009-10-23 23:25:44 +00001035Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1036 NonTypeTemplateParmDecl *D) {
1037 // Substitute into the type of the non-type template parameter.
1038 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001039 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001040 if (DI) {
1041 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1042 D->getDeclName());
1043 if (DI) T = DI->getType();
1044 } else {
1045 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1046 D->getDeclName());
1047 DI = 0;
1048 }
1049 if (T.isNull())
1050 return 0;
1051
1052 // Check that this type is acceptable for a non-type template parameter.
1053 bool Invalid = false;
1054 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1055 if (T.isNull()) {
1056 T = SemaRef.Context.IntTy;
1057 Invalid = true;
1058 }
1059
1060 NonTypeTemplateParmDecl *Param
1061 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1062 D->getDepth() - 1, D->getPosition(),
1063 D->getIdentifier(), T, DI);
1064 if (Invalid)
1065 Param->setInvalidDecl();
1066
1067 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001068
1069 // Introduce this template parameter's instantiation into the instantiation
1070 // scope.
1071 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001072 return Param;
1073}
1074
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001075Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001076TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1077 TemplateTemplateParmDecl *D) {
1078 // Instantiate the template parameter list of the template template parameter.
1079 TemplateParameterList *TempParams = D->getTemplateParameters();
1080 TemplateParameterList *InstParams;
1081 {
1082 // Perform the actual substitution of template parameters within a new,
1083 // local instantiation scope.
1084 Sema::LocalInstantiationScope Scope(SemaRef);
1085 InstParams = SubstTemplateParams(TempParams);
1086 if (!InstParams)
1087 return NULL;
1088 }
1089
1090 // Build the template template parameter.
1091 TemplateTemplateParmDecl *Param
1092 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1093 D->getDepth() - 1, D->getPosition(),
1094 D->getIdentifier(), InstParams);
1095 Param->setDefaultArgument(D->getDefaultArgument());
1096
1097 // Introduce this template parameter's instantiation into the instantiation
1098 // scope.
1099 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1100
1101 return Param;
1102}
1103
Douglas Gregor48c32a72009-11-17 06:07:40 +00001104Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1105 // Using directives are never dependent, so they require no explicit
1106
1107 UsingDirectiveDecl *Inst
1108 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1109 D->getNamespaceKeyLocation(),
1110 D->getQualifierRange(), D->getQualifier(),
1111 D->getIdentLocation(),
1112 D->getNominatedNamespace(),
1113 D->getCommonAncestor());
1114 Owner->addDecl(Inst);
1115 return Inst;
1116}
1117
John McCalled976492009-12-04 22:46:56 +00001118Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1119 // The nested name specifier is non-dependent, so no transformation
1120 // is required.
1121
John McCall9f54ad42009-12-10 09:41:52 +00001122 // We only need to do redeclaration lookups if we're in a class
1123 // scope (in fact, it's not really even possible in non-class
1124 // scopes).
1125 bool CheckRedeclaration = Owner->isRecord();
1126
1127 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1128 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1129
John McCalled976492009-12-04 22:46:56 +00001130 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1131 D->getLocation(),
1132 D->getNestedNameRange(),
1133 D->getUsingLocation(),
1134 D->getTargetNestedNameDecl(),
1135 D->getDeclName(),
1136 D->isTypeName());
1137
1138 CXXScopeSpec SS;
1139 SS.setScopeRep(D->getTargetNestedNameDecl());
1140 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001141
1142 if (CheckRedeclaration) {
1143 Prev.setHideTags(false);
1144 SemaRef.LookupQualifiedName(Prev, Owner);
1145
1146 // Check for invalid redeclarations.
1147 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1148 D->isTypeName(), SS,
1149 D->getLocation(), Prev))
1150 NewUD->setInvalidDecl();
1151
1152 }
1153
1154 if (!NewUD->isInvalidDecl() &&
1155 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001156 D->getLocation()))
1157 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001158
John McCalled976492009-12-04 22:46:56 +00001159 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1160 NewUD->setAccess(D->getAccess());
1161 Owner->addDecl(NewUD);
1162
John McCall9f54ad42009-12-10 09:41:52 +00001163 // Don't process the shadow decls for an invalid decl.
1164 if (NewUD->isInvalidDecl())
1165 return NewUD;
1166
John McCall323c3102009-12-22 22:26:37 +00001167 bool isFunctionScope = Owner->isFunctionOrMethod();
1168
John McCall9f54ad42009-12-10 09:41:52 +00001169 // Process the shadow decls.
1170 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1171 I != E; ++I) {
1172 UsingShadowDecl *Shadow = *I;
1173 NamedDecl *InstTarget =
1174 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1175 TemplateArgs));
1176
1177 if (CheckRedeclaration &&
1178 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1179 continue;
1180
1181 UsingShadowDecl *InstShadow
1182 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1183 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001184
1185 if (isFunctionScope)
1186 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001187 }
John McCalled976492009-12-04 22:46:56 +00001188
1189 return NewUD;
1190}
1191
1192Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001193 // Ignore these; we handle them in bulk when processing the UsingDecl.
1194 return 0;
John McCalled976492009-12-04 22:46:56 +00001195}
1196
John McCall7ba107a2009-11-18 02:36:19 +00001197Decl * TemplateDeclInstantiator
1198 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001199 NestedNameSpecifier *NNS =
1200 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1201 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001202 TemplateArgs);
1203 if (!NNS)
1204 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001206 CXXScopeSpec SS;
1207 SS.setRange(D->getTargetNestedNameRange());
1208 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
1210 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001211 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001212 D->getUsingLoc(), SS, D->getLocation(),
1213 D->getDeclName(), 0,
1214 /*instantiation*/ true,
1215 /*typename*/ true, D->getTypenameLoc());
1216 if (UD)
John McCalled976492009-12-04 22:46:56 +00001217 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1218
John McCall7ba107a2009-11-18 02:36:19 +00001219 return UD;
1220}
1221
1222Decl * TemplateDeclInstantiator
1223 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1224 NestedNameSpecifier *NNS =
1225 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1226 D->getTargetNestedNameRange(),
1227 TemplateArgs);
1228 if (!NNS)
1229 return 0;
1230
1231 CXXScopeSpec SS;
1232 SS.setRange(D->getTargetNestedNameRange());
1233 SS.setScopeRep(NNS);
1234
1235 NamedDecl *UD =
1236 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1237 D->getUsingLoc(), SS, D->getLocation(),
1238 D->getDeclName(), 0,
1239 /*instantiation*/ true,
1240 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001241 if (UD)
John McCalled976492009-12-04 22:46:56 +00001242 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1243
Anders Carlsson0d8df782009-08-29 19:37:28 +00001244 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001245}
1246
John McCallce3ff2b2009-08-25 22:02:44 +00001247Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001248 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001249 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001250 return Instantiator.Visit(D);
1251}
1252
John McCalle29ba202009-08-20 01:44:21 +00001253/// \brief Instantiates a nested template parameter list in the current
1254/// instantiation context.
1255///
1256/// \param L The parameter list to instantiate
1257///
1258/// \returns NULL if there was an error
1259TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001260TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001261 // Get errors for all the parameters before bailing out.
1262 bool Invalid = false;
1263
1264 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001265 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001266 ParamVector Params;
1267 Params.reserve(N);
1268 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1269 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001270 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001271 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001272 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001273 }
1274
1275 // Clean up if we had an error.
1276 if (Invalid) {
1277 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1278 PI != PE; ++PI)
1279 if (*PI)
1280 (*PI)->Destroy(SemaRef.Context);
1281 return NULL;
1282 }
1283
1284 TemplateParameterList *InstL
1285 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1286 L->getLAngleLoc(), &Params.front(), N,
1287 L->getRAngleLoc());
1288 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001289}
John McCalle29ba202009-08-20 01:44:21 +00001290
Douglas Gregored9c0f92009-10-29 00:04:11 +00001291/// \brief Instantiate the declaration of a class template partial
1292/// specialization.
1293///
1294/// \param ClassTemplate the (instantiated) class template that is partially
1295// specialized by the instantiation of \p PartialSpec.
1296///
1297/// \param PartialSpec the (uninstantiated) class template partial
1298/// specialization that we are instantiating.
1299///
1300/// \returns true if there was an error, false otherwise.
1301bool
1302TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1303 ClassTemplateDecl *ClassTemplate,
1304 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001305 // Create a local instantiation scope for this class template partial
1306 // specialization, which will contain the instantiations of the template
1307 // parameters.
1308 Sema::LocalInstantiationScope Scope(SemaRef);
1309
Douglas Gregored9c0f92009-10-29 00:04:11 +00001310 // Substitute into the template parameters of the class template partial
1311 // specialization.
1312 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1313 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1314 if (!InstParams)
1315 return true;
1316
1317 // Substitute into the template arguments of the class template partial
1318 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001319 const TemplateArgumentLoc *PartialSpecTemplateArgs
1320 = PartialSpec->getTemplateArgsAsWritten();
1321 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1322
John McCalld5532b62009-11-23 01:53:49 +00001323 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001324 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001325 TemplateArgumentLoc Loc;
1326 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001327 return true;
John McCalld5532b62009-11-23 01:53:49 +00001328 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001329 }
1330
1331
1332 // Check that the template argument list is well-formed for this
1333 // class template.
1334 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1335 InstTemplateArgs.size());
1336 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1337 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001338 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001339 false,
1340 Converted))
1341 return true;
1342
1343 // Figure out where to insert this class template partial specialization
1344 // in the member template's set of class template partial specializations.
1345 llvm::FoldingSetNodeID ID;
1346 ClassTemplatePartialSpecializationDecl::Profile(ID,
1347 Converted.getFlatArguments(),
1348 Converted.flatSize(),
1349 SemaRef.Context);
1350 void *InsertPos = 0;
1351 ClassTemplateSpecializationDecl *PrevDecl
1352 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1353 InsertPos);
1354
1355 // Build the canonical type that describes the converted template
1356 // arguments of the class template partial specialization.
1357 QualType CanonType
1358 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1359 Converted.getFlatArguments(),
1360 Converted.flatSize());
1361
1362 // Build the fully-sugared type for this class template
1363 // specialization as the user wrote in the specialization
1364 // itself. This means that we'll pretty-print the type retrieved
1365 // from the specialization's declaration the way that the user
1366 // actually wrote the specialization, rather than formatting the
1367 // name based on the "canonical" representation used to store the
1368 // template arguments in the specialization.
1369 QualType WrittenTy
1370 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001371 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001372 CanonType);
1373
1374 if (PrevDecl) {
1375 // We've already seen a partial specialization with the same template
1376 // parameters and template arguments. This can happen, for example, when
1377 // substituting the outer template arguments ends up causing two
1378 // class template partial specializations of a member class template
1379 // to have identical forms, e.g.,
1380 //
1381 // template<typename T, typename U>
1382 // struct Outer {
1383 // template<typename X, typename Y> struct Inner;
1384 // template<typename Y> struct Inner<T, Y>;
1385 // template<typename Y> struct Inner<U, Y>;
1386 // };
1387 //
1388 // Outer<int, int> outer; // error: the partial specializations of Inner
1389 // // have the same signature.
1390 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1391 << WrittenTy;
1392 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1393 << SemaRef.Context.getTypeDeclType(PrevDecl);
1394 return true;
1395 }
1396
1397
1398 // Create the class template partial specialization declaration.
1399 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1400 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1401 PartialSpec->getLocation(),
1402 InstParams,
1403 ClassTemplate,
1404 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001405 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001406 0);
1407 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1408 InstPartialSpec->setTypeAsWritten(WrittenTy);
1409
1410 // Add this partial specialization to the set of class template partial
1411 // specializations.
1412 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1413 InsertPos);
1414 return false;
1415}
1416
John McCallce3ff2b2009-08-25 22:02:44 +00001417/// \brief Does substitution on the type of the given function, including
1418/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001419///
John McCallce3ff2b2009-08-25 22:02:44 +00001420/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001421///
1422/// \param Params the instantiated parameter declarations
1423
John McCallce3ff2b2009-08-25 22:02:44 +00001424/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001425/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001426QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001427TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001428 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1429 bool InvalidDecl = false;
1430
John McCallce3ff2b2009-08-25 22:02:44 +00001431 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001432 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001433 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001434 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001435 PEnd = D->param_end();
1436 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001437 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001438 if (PInst->getType()->isVoidType()) {
1439 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1440 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001441 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001442 PInst->getType(),
1443 diag::err_abstract_type_in_decl,
1444 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001445 PInst->setInvalidDecl();
1446
1447 Params.push_back(PInst);
1448 ParamTys.push_back(PInst->getType());
1449
1450 if (PInst->isInvalidDecl())
1451 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001452 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001453 InvalidDecl = true;
1454 }
1455
1456 // FIXME: Deallocate dead declarations.
1457 if (InvalidDecl)
1458 return QualType();
1459
John McCall183700f2009-09-21 23:43:11 +00001460 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001461 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001462 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001463 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1464 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001465 if (ResultType.isNull())
1466 return QualType();
1467
Jay Foadbeaaccd2009-05-21 09:52:38 +00001468 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001469 Proto->isVariadic(), Proto->getTypeQuals(),
1470 D->getLocation(), D->getDeclName());
1471}
1472
Mike Stump1eb44332009-09-09 15:08:12 +00001473/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001474/// declaration (New) from the corresponding fields of its template (Tmpl).
1475///
1476/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001477bool
1478TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001479 FunctionDecl *Tmpl) {
1480 if (Tmpl->isDeleted())
1481 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Douglas Gregorcca9e962009-07-01 22:01:06 +00001483 // If we are performing substituting explicitly-specified template arguments
1484 // or deduced template arguments into a function template and we reach this
1485 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001486 // to keeping the new function template specialization. We therefore
1487 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001488 // into a template instantiation for this specific function template
1489 // specialization, which is not a SFINAE context, so that we diagnose any
1490 // further errors in the declaration itself.
1491 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1492 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1493 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1494 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001495 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001496 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001497 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001498 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001499 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001500 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1501 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001502 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001503 }
1504 }
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001506 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1507 assert(Proto && "Function template without prototype?");
1508
1509 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1510 Proto->getNoReturnAttr()) {
1511 // The function has an exception specification or a "noreturn"
1512 // attribute. Substitute into each of the exception types.
1513 llvm::SmallVector<QualType, 4> Exceptions;
1514 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1515 // FIXME: Poor location information!
1516 QualType T
1517 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1518 New->getLocation(), New->getDeclName());
1519 if (T.isNull() ||
1520 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1521 continue;
1522
1523 Exceptions.push_back(T);
1524 }
1525
1526 // Rebuild the function type
1527
1528 const FunctionProtoType *NewProto
1529 = New->getType()->getAs<FunctionProtoType>();
1530 assert(NewProto && "Template instantiation without function prototype?");
1531 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1532 NewProto->arg_type_begin(),
1533 NewProto->getNumArgs(),
1534 NewProto->isVariadic(),
1535 NewProto->getTypeQuals(),
1536 Proto->hasExceptionSpec(),
1537 Proto->hasAnyExceptionSpec(),
1538 Exceptions.size(),
1539 Exceptions.data(),
1540 Proto->getNoReturnAttr()));
1541 }
1542
Douglas Gregore53060f2009-06-25 22:08:12 +00001543 return false;
1544}
1545
Douglas Gregor5545e162009-03-24 00:38:23 +00001546/// \brief Initializes common fields of an instantiated method
1547/// declaration (New) from the corresponding fields of its template
1548/// (Tmpl).
1549///
1550/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001551bool
1552TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001553 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001554 if (InitFunctionInstantiation(New, Tmpl))
1555 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Douglas Gregor5545e162009-03-24 00:38:23 +00001557 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1558 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001559 if (Tmpl->isVirtualAsWritten())
1560 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001561
1562 // FIXME: attributes
1563 // FIXME: New needs a pointer to Tmpl
1564 return false;
1565}
Douglas Gregora58861f2009-05-13 20:28:22 +00001566
1567/// \brief Instantiate the definition of the given function from its
1568/// template.
1569///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001570/// \param PointOfInstantiation the point at which the instantiation was
1571/// required. Note that this is not precisely a "point of instantiation"
1572/// for the function, but it's close.
1573///
Douglas Gregora58861f2009-05-13 20:28:22 +00001574/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001575/// function template specialization or member function of a class template
1576/// specialization.
1577///
1578/// \param Recursive if true, recursively instantiates any functions that
1579/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001580///
1581/// \param DefinitionRequired if true, then we are performing an explicit
1582/// instantiation where the body of the function is required. Complain if
1583/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001584void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001585 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001586 bool Recursive,
1587 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001588 if (Function->isInvalidDecl())
1589 return;
1590
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001591 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001593 // Never instantiate an explicit specialization.
1594 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1595 return;
1596
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001597 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001598 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001599 Stmt *Pattern = 0;
1600 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001601 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001602
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001603 if (!Pattern) {
1604 if (DefinitionRequired) {
1605 if (Function->getPrimaryTemplate())
1606 Diag(PointOfInstantiation,
1607 diag::err_explicit_instantiation_undefined_func_template)
1608 << Function->getPrimaryTemplate();
1609 else
1610 Diag(PointOfInstantiation,
1611 diag::err_explicit_instantiation_undefined_member)
1612 << 1 << Function->getDeclName() << Function->getDeclContext();
1613
1614 if (PatternDecl)
1615 Diag(PatternDecl->getLocation(),
1616 diag::note_explicit_instantiation_here);
1617 }
1618
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001619 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001620 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001621
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001622 // C++0x [temp.explicit]p9:
1623 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001624 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001625 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001626 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001627 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001628 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001629 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001631 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1632 if (Inst)
1633 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001634
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001635 // If we're performing recursive template instantiation, create our own
1636 // queue of pending implicit instantiations that we will instantiate later,
1637 // while we're still within our own instantiation context.
1638 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1639 if (Recursive)
1640 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001642 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1643
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001644 // Introduce a new scope where local variable instantiations will be
1645 // recorded.
1646 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001648 // Introduce the instantiated function parameters into the local
1649 // instantiation scope.
1650 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1651 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1652 Function->getParamDecl(I));
1653
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001654 // Enter the scope of this instantiation. We don't use
1655 // PushDeclContext because we don't have a scope.
1656 DeclContext *PreviousContext = CurContext;
1657 CurContext = Function;
1658
Mike Stump1eb44332009-09-09 15:08:12 +00001659 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001660 getTemplateInstantiationArgs(Function);
1661
1662 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001663 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001664 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1665 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1666 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001667 }
1668
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001669 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001670 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001671
Douglas Gregor52604ab2009-09-11 21:19:12 +00001672 if (Body.isInvalid())
1673 Function->setInvalidDecl();
1674
Mike Stump1eb44332009-09-09 15:08:12 +00001675 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001676 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001677
1678 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001679
1680 DeclGroupRef DG(Function);
1681 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001683 if (Recursive) {
1684 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001685 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001686 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001688 // Restore the set of pending implicit instantiations.
1689 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1690 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001691}
1692
1693/// \brief Instantiate the definition of the given variable from its
1694/// template.
1695///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001696/// \param PointOfInstantiation the point at which the instantiation was
1697/// required. Note that this is not precisely a "point of instantiation"
1698/// for the function, but it's close.
1699///
1700/// \param Var the already-instantiated declaration of a static member
1701/// variable of a class template specialization.
1702///
1703/// \param Recursive if true, recursively instantiates any functions that
1704/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001705///
1706/// \param DefinitionRequired if true, then we are performing an explicit
1707/// instantiation where an out-of-line definition of the member variable
1708/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001709void Sema::InstantiateStaticDataMemberDefinition(
1710 SourceLocation PointOfInstantiation,
1711 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001712 bool Recursive,
1713 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001714 if (Var->isInvalidDecl())
1715 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Douglas Gregor7caa6822009-07-24 20:34:43 +00001717 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001718 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001719 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001720 assert(Def->isStaticDataMember() && "Not a static data member?");
1721 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Douglas Gregor0d035142009-10-27 18:42:08 +00001723 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001724 // We did not find an out-of-line definition of this static data member,
1725 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001726 // instantiate this definition (or provide a specialization for it) in
1727 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001728 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001729 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001730 Diag(PointOfInstantiation,
1731 diag::err_explicit_instantiation_undefined_member)
1732 << 2 << Var->getDeclName() << Var->getDeclContext();
1733 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1734 }
1735
Douglas Gregor7caa6822009-07-24 20:34:43 +00001736 return;
1737 }
1738
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001739 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001740 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001741 return;
1742
1743 // C++0x [temp.explicit]p9:
1744 // Except for inline functions, other explicit instantiation declarations
1745 // have the effect of suppressing the implicit instantiation of the entity
1746 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001747 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001748 == TSK_ExplicitInstantiationDeclaration)
1749 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor7caa6822009-07-24 20:34:43 +00001751 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1752 if (Inst)
1753 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregor7caa6822009-07-24 20:34:43 +00001755 // If we're performing recursive template instantiation, create our own
1756 // queue of pending implicit instantiations that we will instantiate later,
1757 // while we're still within our own instantiation context.
1758 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1759 if (Recursive)
1760 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor7caa6822009-07-24 20:34:43 +00001762 // Enter the scope of this instantiation. We don't use
1763 // PushDeclContext because we don't have a scope.
1764 DeclContext *PreviousContext = CurContext;
1765 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001767 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001768 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001769 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001770 CurContext = PreviousContext;
1771
1772 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001773 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001774 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1775 assert(MSInfo && "Missing member specialization information?");
1776 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1777 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001778 DeclGroupRef DG(Var);
1779 Consumer.HandleTopLevelDecl(DG);
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Douglas Gregor7caa6822009-07-24 20:34:43 +00001782 if (Recursive) {
1783 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001784 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001785 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor7caa6822009-07-24 20:34:43 +00001787 // Restore the set of pending implicit instantiations.
1788 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001789 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001790}
Douglas Gregor815215d2009-05-27 05:35:12 +00001791
Anders Carlsson09025312009-08-29 05:16:22 +00001792void
1793Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1794 const CXXConstructorDecl *Tmpl,
1795 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Anders Carlsson09025312009-08-29 05:16:22 +00001797 llvm::SmallVector<MemInitTy*, 4> NewInits;
1798
1799 // Instantiate all the initializers.
1800 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001801 InitsEnd = Tmpl->init_end();
1802 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001803 CXXBaseOrMemberInitializer *Init = *Inits;
1804
1805 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Anders Carlsson09025312009-08-29 05:16:22 +00001807 // Instantiate all the arguments.
1808 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1809 Args != ArgsEnd; ++Args) {
1810 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1811
1812 if (NewArg.isInvalid())
1813 New->setInvalidDecl();
1814 else
1815 NewArgs.push_back(NewArg.takeAs<Expr>());
1816 }
1817
1818 MemInitResult NewInit;
1819
1820 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001821 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001822 TemplateArgs,
1823 Init->getSourceLocation(),
1824 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001825 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001826 New->setInvalidDecl();
1827 continue;
1828 }
1829
John McCalla93c9342009-12-07 02:54:59 +00001830 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001831 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001832 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001833 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001834 Init->getRParenLoc(),
1835 New->getParent());
1836 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001837 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001839 // Is this an anonymous union?
1840 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001841 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001842 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001843 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1844 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001845
1846 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001847 NewArgs.size(),
1848 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001849 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001850 Init->getRParenLoc());
1851 }
1852
1853 if (NewInit.isInvalid())
1854 New->setInvalidDecl();
1855 else {
1856 // FIXME: It would be nice if ASTOwningVector had a release function.
1857 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anders Carlsson09025312009-08-29 05:16:22 +00001859 NewInits.push_back((MemInitTy *)NewInit.get());
1860 }
1861 }
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Anders Carlsson09025312009-08-29 05:16:22 +00001863 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001864 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001865 /*FIXME: ColonLoc */
1866 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001867 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001868}
1869
John McCall52a575a2009-08-29 08:11:13 +00001870// TODO: this could be templated if the various decl types used the
1871// same method name.
1872static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1873 ClassTemplateDecl *Instance) {
1874 Pattern = Pattern->getCanonicalDecl();
1875
1876 do {
1877 Instance = Instance->getCanonicalDecl();
1878 if (Pattern == Instance) return true;
1879 Instance = Instance->getInstantiatedFromMemberTemplate();
1880 } while (Instance);
1881
1882 return false;
1883}
1884
Douglas Gregor0d696532009-09-28 06:34:35 +00001885static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1886 FunctionTemplateDecl *Instance) {
1887 Pattern = Pattern->getCanonicalDecl();
1888
1889 do {
1890 Instance = Instance->getCanonicalDecl();
1891 if (Pattern == Instance) return true;
1892 Instance = Instance->getInstantiatedFromMemberTemplate();
1893 } while (Instance);
1894
1895 return false;
1896}
1897
Douglas Gregored9c0f92009-10-29 00:04:11 +00001898static bool
1899isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1900 ClassTemplatePartialSpecializationDecl *Instance) {
1901 Pattern
1902 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1903 do {
1904 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1905 Instance->getCanonicalDecl());
1906 if (Pattern == Instance)
1907 return true;
1908 Instance = Instance->getInstantiatedFromMember();
1909 } while (Instance);
1910
1911 return false;
1912}
1913
John McCall52a575a2009-08-29 08:11:13 +00001914static bool isInstantiationOf(CXXRecordDecl *Pattern,
1915 CXXRecordDecl *Instance) {
1916 Pattern = Pattern->getCanonicalDecl();
1917
1918 do {
1919 Instance = Instance->getCanonicalDecl();
1920 if (Pattern == Instance) return true;
1921 Instance = Instance->getInstantiatedFromMemberClass();
1922 } while (Instance);
1923
1924 return false;
1925}
1926
1927static bool isInstantiationOf(FunctionDecl *Pattern,
1928 FunctionDecl *Instance) {
1929 Pattern = Pattern->getCanonicalDecl();
1930
1931 do {
1932 Instance = Instance->getCanonicalDecl();
1933 if (Pattern == Instance) return true;
1934 Instance = Instance->getInstantiatedFromMemberFunction();
1935 } while (Instance);
1936
1937 return false;
1938}
1939
1940static bool isInstantiationOf(EnumDecl *Pattern,
1941 EnumDecl *Instance) {
1942 Pattern = Pattern->getCanonicalDecl();
1943
1944 do {
1945 Instance = Instance->getCanonicalDecl();
1946 if (Pattern == Instance) return true;
1947 Instance = Instance->getInstantiatedFromMemberEnum();
1948 } while (Instance);
1949
1950 return false;
1951}
1952
John McCalled976492009-12-04 22:46:56 +00001953static bool isInstantiationOf(UsingShadowDecl *Pattern,
1954 UsingShadowDecl *Instance,
1955 ASTContext &C) {
1956 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1957}
1958
1959static bool isInstantiationOf(UsingDecl *Pattern,
1960 UsingDecl *Instance,
1961 ASTContext &C) {
1962 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1963}
1964
John McCall7ba107a2009-11-18 02:36:19 +00001965static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1966 UsingDecl *Instance,
1967 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001968 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001969}
1970
1971static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001972 UsingDecl *Instance,
1973 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001974 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001975}
1976
John McCall52a575a2009-08-29 08:11:13 +00001977static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1978 VarDecl *Instance) {
1979 assert(Instance->isStaticDataMember());
1980
1981 Pattern = Pattern->getCanonicalDecl();
1982
1983 do {
1984 Instance = Instance->getCanonicalDecl();
1985 if (Pattern == Instance) return true;
1986 Instance = Instance->getInstantiatedFromStaticDataMember();
1987 } while (Instance);
1988
1989 return false;
1990}
1991
John McCalled976492009-12-04 22:46:56 +00001992// Other is the prospective instantiation
1993// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001994static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001995 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001996 if (UnresolvedUsingTypenameDecl *UUD
1997 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1998 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1999 return isInstantiationOf(UUD, UD, Ctx);
2000 }
2001 }
2002
2003 if (UnresolvedUsingValueDecl *UUD
2004 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002005 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2006 return isInstantiationOf(UUD, UD, Ctx);
2007 }
2008 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002009
Anders Carlsson0d8df782009-08-29 19:37:28 +00002010 return false;
2011 }
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall52a575a2009-08-29 08:11:13 +00002013 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2014 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
John McCall52a575a2009-08-29 08:11:13 +00002016 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2017 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002018
John McCall52a575a2009-08-29 08:11:13 +00002019 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2020 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002021
Douglas Gregor7caa6822009-07-24 20:34:43 +00002022 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002023 if (Var->isStaticDataMember())
2024 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2025
2026 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2027 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002028
Douglas Gregor0d696532009-09-28 06:34:35 +00002029 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2030 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2031
Douglas Gregored9c0f92009-10-29 00:04:11 +00002032 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2033 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2034 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2035 PartialSpec);
2036
Anders Carlssond8b285f2009-09-01 04:26:58 +00002037 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2038 if (!Field->getDeclName()) {
2039 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002040 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002041 cast<FieldDecl>(D);
2042 }
2043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
John McCalled976492009-12-04 22:46:56 +00002045 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2046 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2047
2048 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2049 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2050
Douglas Gregor815215d2009-05-27 05:35:12 +00002051 return D->getDeclName() && isa<NamedDecl>(Other) &&
2052 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2053}
2054
2055template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002056static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002057 NamedDecl *D,
2058 ForwardIterator first,
2059 ForwardIterator last) {
2060 for (; first != last; ++first)
2061 if (isInstantiationOf(Ctx, D, *first))
2062 return cast<NamedDecl>(*first);
2063
2064 return 0;
2065}
2066
John McCall02cace72009-08-28 07:59:38 +00002067/// \brief Finds the instantiation of the given declaration context
2068/// within the current instantiation.
2069///
2070/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002071DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2072 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002073 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002074 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002075 return cast_or_null<DeclContext>(ID);
2076 } else return DC;
2077}
2078
Douglas Gregored961e72009-05-27 17:54:46 +00002079/// \brief Find the instantiation of the given declaration within the
2080/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002081///
2082/// This routine is intended to be used when \p D is a declaration
2083/// referenced from within a template, that needs to mapped into the
2084/// corresponding declaration within an instantiation. For example,
2085/// given:
2086///
2087/// \code
2088/// template<typename T>
2089/// struct X {
2090/// enum Kind {
2091/// KnownValue = sizeof(T)
2092/// };
2093///
2094/// bool getKind() const { return KnownValue; }
2095/// };
2096///
2097/// template struct X<int>;
2098/// \endcode
2099///
2100/// In the instantiation of X<int>::getKind(), we need to map the
2101/// EnumConstantDecl for KnownValue (which refers to
2102/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002103/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2104/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002105NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2106 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002107 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002108 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2109 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2110 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002111 // D is a local of some kind. Look into the map of local
2112 // declarations to their instantiations.
2113 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2114 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002115
Douglas Gregore95b4092009-09-16 18:34:49 +00002116 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2117 if (!Record->isDependentContext())
2118 return D;
2119
2120 // If the RecordDecl is actually the injected-class-name or a "templated"
2121 // declaration for a class template or class template partial
2122 // specialization, substitute into the injected-class-name of the
2123 // class template or partial specialization to find the new DeclContext.
2124 QualType T;
2125 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2126
2127 if (ClassTemplate) {
2128 T = ClassTemplate->getInjectedClassNameType(Context);
2129 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2130 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2131 T = Context.getTypeDeclType(Record);
2132 ClassTemplate = PartialSpec->getSpecializedTemplate();
2133 }
2134
2135 if (!T.isNull()) {
2136 // Substitute into the injected-class-name to get the type corresponding
2137 // to the instantiation we want. This substitution should never fail,
2138 // since we know we can instantiate the injected-class-name or we wouldn't
2139 // have gotten to the injected-class-name!
2140 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2141 // instantiation in the common case?
2142 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2143 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2144
2145 if (!T->isDependentType()) {
2146 assert(T->isRecordType() && "Instantiation must produce a record type");
2147 return T->getAs<RecordType>()->getDecl();
2148 }
2149
2150 // We are performing "partial" template instantiation to create the
2151 // member declarations for the members of a class template
2152 // specialization. Therefore, D is actually referring to something in
2153 // the current instantiation. Look through the current context,
2154 // which contains actual instantiations, to find the instantiation of
2155 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002156 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002157 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002158 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002159 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002160 if (isInstantiationOf(ClassTemplate,
2161 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002162 return Spec;
2163 }
2164
Mike Stump1eb44332009-09-09 15:08:12 +00002165 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002166 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002167 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002168 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002169
2170 // Fall through to deal with other dependent record types (e.g.,
2171 // anonymous unions in class templates).
2172 }
John McCall52a575a2009-08-29 08:11:13 +00002173
Douglas Gregore95b4092009-09-16 18:34:49 +00002174 if (!ParentDC->isDependentContext())
2175 return D;
2176
2177 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002178 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002179 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Douglas Gregor815215d2009-05-27 05:35:12 +00002181 if (ParentDC != D->getDeclContext()) {
2182 // We performed some kind of instantiation in the parent context,
2183 // so now we need to look into the instantiated parent context to
2184 // find the instantiation of the declaration D.
2185 NamedDecl *Result = 0;
2186 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002187 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002188 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2189 } else {
2190 // Since we don't have a name for the entity we're looking for,
2191 // our only option is to walk through all of the declarations to
2192 // find that name. This will occur in a few cases:
2193 //
2194 // - anonymous struct/union within a template
2195 // - unnamed class/struct/union/enum within a template
2196 //
2197 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002198 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002199 ParentDC->decls_begin(),
2200 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
John McCall9f54ad42009-12-10 09:41:52 +00002203 // UsingShadowDecls can instantiate to nothing because of using hiding.
2204 assert((Result || isa<UsingShadowDecl>(D))
2205 && "Unable to find instantiation of declaration!");
2206
Douglas Gregor815215d2009-05-27 05:35:12 +00002207 D = Result;
2208 }
2209
Douglas Gregor815215d2009-05-27 05:35:12 +00002210 return D;
2211}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002212
Mike Stump1eb44332009-09-09 15:08:12 +00002213/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002214/// instantiations we have seen until this point.
2215void Sema::PerformPendingImplicitInstantiations() {
2216 while (!PendingImplicitInstantiations.empty()) {
2217 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002218 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor7caa6822009-07-24 20:34:43 +00002220 // Instantiate function definitions
2221 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002222 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002223 Function->getLocation(), *this,
2224 Context.getSourceManager(),
2225 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002227 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002228 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002229 continue;
2230 }
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Douglas Gregor7caa6822009-07-24 20:34:43 +00002232 // Instantiate static data member definitions.
2233 VarDecl *Var = cast<VarDecl>(Inst.first);
2234 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002235
Mike Stump1eb44332009-09-09 15:08:12 +00002236 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002237 Var->getLocation(), *this,
2238 Context.getSourceManager(),
2239 "instantiating static data member "
2240 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Douglas Gregor7caa6822009-07-24 20:34:43 +00002242 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002243 }
2244}