blob: 2ca4810055e8727ee65740d547ce04b26a01322a [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);
404 else
405 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000406 if (!NewND) return 0;
407
408 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
John McCall02cace72009-08-28 07:59:38 +0000411 FriendDecl *FD =
412 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
413 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000414 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000415 Owner->addDecl(FD);
416 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000417}
418
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
420 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Douglas Gregorac7610d2009-06-22 20:57:11 +0000422 // The expression in a static assertion is not potentially evaluated.
423 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000425 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000426 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 if (InstantiatedAssertExpr.isInvalid())
428 return 0;
429
Douglas Gregor43d9d922009-08-08 01:41:12 +0000430 OwningExprResult Message(SemaRef, D->getMessage());
431 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000432 Decl *StaticAssert
433 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000434 move(InstantiatedAssertExpr),
435 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000436 return StaticAssert;
437}
438
439Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000440 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000442 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000443 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000444 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000445 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000446 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000447 Enum->startDefinition();
448
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000449 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450
451 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000452 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
453 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 EC != ECEnd; ++EC) {
455 // The specified value for the enumerator.
456 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000457 if (Expr *UninstValue = EC->getInitExpr()) {
458 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000459 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000460 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
John McCallce3ff2b2009-08-25 22:02:44 +0000462 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000463 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464
465 // Drop the initial value and continue.
466 bool isInvalid = false;
467 if (Value.isInvalid()) {
468 Value = SemaRef.Owned((Expr *)0);
469 isInvalid = true;
470 }
471
Mike Stump1eb44332009-09-09 15:08:12 +0000472 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000473 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
474 EC->getLocation(), EC->getIdentifier(),
475 move(Value));
476
477 if (isInvalid) {
478 if (EnumConst)
479 EnumConst->setInvalidDecl();
480 Enum->setInvalidDecl();
481 }
482
483 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000484 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000485 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000486 LastEnumConst = EnumConst;
487 }
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000490 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000491 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000492 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
493 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000494 &Enumerators[0], Enumerators.size(),
495 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000496
497 return Enum;
498}
499
Douglas Gregor6477b692009-03-25 15:04:13 +0000500Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
501 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
502 return 0;
503}
504
Douglas Gregored9c0f92009-10-29 00:04:11 +0000505namespace {
506 class SortDeclByLocation {
507 SourceManager &SourceMgr;
508
509 public:
510 explicit SortDeclByLocation(SourceManager &SourceMgr)
511 : SourceMgr(SourceMgr) { }
512
513 bool operator()(const Decl *X, const Decl *Y) const {
514 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
515 Y->getLocation());
516 }
517 };
518}
519
John McCalle29ba202009-08-20 01:44:21 +0000520Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000521 // Create a local instantiation scope for this class template, which
522 // will contain the instantiations of the template parameters.
523 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000524 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000525 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000526 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000527 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000528
529 CXXRecordDecl *Pattern = D->getTemplatedDecl();
530 CXXRecordDecl *RecordInst
531 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
532 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000533 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
534 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000535
536 ClassTemplateDecl *Inst
537 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
538 D->getIdentifier(), InstParams, RecordInst, 0);
539 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000540 if (D->getFriendObjectKind())
541 Inst->setObjectOfFriendDecl(true);
542 else
543 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000544 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000545
546 // Trigger creation of the type for the instantiation.
547 SemaRef.Context.getTypeDeclType(RecordInst);
548
Douglas Gregor259571e2009-10-30 22:42:42 +0000549 // Finish handling of friends.
550 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000551 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000552 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000553
John McCalle29ba202009-08-20 01:44:21 +0000554 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000555
556 // First, we sort the partial specializations by location, so
557 // that we instantiate them in the order they were declared.
558 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
559 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
560 P = D->getPartialSpecializations().begin(),
561 PEnd = D->getPartialSpecializations().end();
562 P != PEnd; ++P)
563 PartialSpecs.push_back(&*P);
564 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
565 SortDeclByLocation(SemaRef.SourceMgr));
566
567 // Instantiate all of the partial specializations of this member class
568 // template.
569 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
570 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
571
John McCalle29ba202009-08-20 01:44:21 +0000572 return Inst;
573}
574
Douglas Gregord60e1052009-08-27 16:57:43 +0000575Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000576TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
577 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000578 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
579
580 // Lookup the already-instantiated declaration in the instantiation
581 // of the class template and return that.
582 DeclContext::lookup_result Found
583 = Owner->lookup(ClassTemplate->getDeclName());
584 if (Found.first == Found.second)
585 return 0;
586
587 ClassTemplateDecl *InstClassTemplate
588 = dyn_cast<ClassTemplateDecl>(*Found.first);
589 if (!InstClassTemplate)
590 return 0;
591
592 Decl *DCanon = D->getCanonicalDecl();
593 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
594 P = InstClassTemplate->getPartialSpecializations().begin(),
595 PEnd = InstClassTemplate->getPartialSpecializations().end();
596 P != PEnd; ++P) {
597 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
598 return &*P;
599 }
600
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000601 return 0;
602}
603
604Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000605TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000606 // Create a local instantiation scope for this function template, which
607 // will contain the instantiations of the template parameters and then get
608 // merged with the local instantiation scope for the function template
609 // itself.
610 Sema::LocalInstantiationScope Scope(SemaRef);
611
Douglas Gregord60e1052009-08-27 16:57:43 +0000612 TemplateParameterList *TempParams = D->getTemplateParameters();
613 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000614 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000615 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000616
Douglas Gregora735b202009-10-13 14:39:41 +0000617 FunctionDecl *Instantiated = 0;
618 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
619 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
620 InstParams));
621 else
622 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
623 D->getTemplatedDecl(),
624 InstParams));
625
626 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000627 return 0;
628
Mike Stump1eb44332009-09-09 15:08:12 +0000629 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000630 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000631 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000632 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000633 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000634 assert(InstTemplate &&
635 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000636
637 // Link the instantiation back to the pattern *unless* this is a
638 // non-definition friend declaration.
639 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
640 !(InstTemplate->getFriendObjectKind() &&
641 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000642 InstTemplate->setInstantiatedFromMemberTemplate(D);
643
644 // Add non-friends into the owner.
645 if (!InstTemplate->getFriendObjectKind())
646 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000647 return InstTemplate;
648}
649
Douglas Gregord475b8d2009-03-25 21:17:03 +0000650Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
651 CXXRecordDecl *PrevDecl = 0;
652 if (D->isInjectedClassName())
653 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000654 else if (D->getPreviousDeclaration()) {
655 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
656 TemplateArgs);
657 if (!Prev) return 0;
658 PrevDecl = cast<CXXRecordDecl>(Prev);
659 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000660
661 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000662 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000663 D->getLocation(), D->getIdentifier(),
664 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000665 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000666 // FIXME: Check against AS_none is an ugly hack to work around the issue that
667 // the tag decls introduced by friend class declarations don't have an access
668 // specifier. Remove once this area of the code gets sorted out.
669 if (D->getAccess() != AS_none)
670 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000671 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000672 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000673
John McCall02cace72009-08-28 07:59:38 +0000674 // If the original function was part of a friend declaration,
675 // inherit its namespace state.
676 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
677 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
678
Anders Carlssond8b285f2009-09-01 04:26:58 +0000679 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
680
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000681 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000682 return Record;
683}
684
John McCall02cace72009-08-28 07:59:38 +0000685/// Normal class members are of more specific types and therefore
686/// don't make it here. This function serves two purposes:
687/// 1) instantiating function templates
688/// 2) substituting friend declarations
689/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000690 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
691 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000692 // Check whether there is already a function template specialization for
693 // this declaration.
694 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
695 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000696 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000697 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000698 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000699 TemplateArgs.getInnermost().getFlatArgumentList(),
700 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000701 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000702
703 FunctionTemplateSpecializationInfo *Info
704 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000705 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Douglas Gregor127102b2009-06-29 20:59:39 +0000707 // If we already have a function template specialization, return it.
708 if (Info)
709 return Info->Function;
710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregor550d9b22009-10-31 17:21:17 +0000712 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Douglas Gregore53060f2009-06-25 22:08:12 +0000714 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000715 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000716 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000717 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000718
Douglas Gregore53060f2009-06-25 22:08:12 +0000719 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000720 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
721 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000722 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000723 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000724 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000725 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000726 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000727 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregore53060f2009-06-25 22:08:12 +0000729 // Attach the parameters
730 for (unsigned P = 0; P < Params.size(); ++P)
731 Params[P]->setOwningFunction(Function);
732 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000733
Douglas Gregora735b202009-10-13 14:39:41 +0000734 if (TemplateParams) {
735 // Our resulting instantiation is actually a function template, since we
736 // are substituting only the outer template parameters. For example, given
737 //
738 // template<typename T>
739 // struct X {
740 // template<typename U> friend void f(T, U);
741 // };
742 //
743 // X<int> x;
744 //
745 // We are instantiating the friend function template "f" within X<int>,
746 // which means substituting int for T, but leaving "f" as a friend function
747 // template.
748 // Build the function template itself.
749 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
750 Function->getLocation(),
751 Function->getDeclName(),
752 TemplateParams, Function);
753 Function->setDescribedFunctionTemplate(FunctionTemplate);
754 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000755 } else if (FunctionTemplate) {
756 // Record this function template specialization.
757 Function->setFunctionTemplateSpecialization(SemaRef.Context,
758 FunctionTemplate,
759 &TemplateArgs.getInnermost(),
760 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000761 }
Douglas Gregora735b202009-10-13 14:39:41 +0000762
Douglas Gregore53060f2009-06-25 22:08:12 +0000763 if (InitFunctionInstantiation(Function, D))
764 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregore53060f2009-06-25 22:08:12 +0000766 bool Redeclaration = false;
767 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000768
John McCall68263142009-11-18 22:49:29 +0000769 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
770 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
771
Douglas Gregora735b202009-10-13 14:39:41 +0000772 if (TemplateParams || !FunctionTemplate) {
773 // Look only into the namespace where the friend would be declared to
774 // find a previous declaration. This is the innermost enclosing namespace,
775 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000776 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000777
Douglas Gregora735b202009-10-13 14:39:41 +0000778 // In C++, the previous declaration we find might be a tag type
779 // (class or enum). In this case, the new declaration will hide the
780 // tag type. Note that this does does not apply if we're declaring a
781 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000782 if (Previous.isSingleTagDecl())
783 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000784 }
785
John McCall9f54ad42009-12-10 09:41:52 +0000786 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
787 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000788 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000789
Douglas Gregora735b202009-10-13 14:39:41 +0000790 // If the original function was part of a friend declaration,
791 // inherit its namespace state and add it to the owner.
792 NamedDecl *FromFriendD
793 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
794 if (FromFriendD->getFriendObjectKind()) {
795 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000796 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000797 if (TemplateParams) {
798 ToFriendD = cast<NamedDecl>(FunctionTemplate);
799 PrevDecl = FunctionTemplate->getPreviousDeclaration();
800 } else {
801 ToFriendD = Function;
802 PrevDecl = Function->getPreviousDeclaration();
803 }
804 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
805 if (!Owner->isDependentContext() && !PrevDecl)
806 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
807
808 if (!TemplateParams)
809 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
810 }
811
Douglas Gregore53060f2009-06-25 22:08:12 +0000812 return Function;
813}
814
Douglas Gregord60e1052009-08-27 16:57:43 +0000815Decl *
816TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
817 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000818 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
819 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000820 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000821 // We are creating a function template specialization from a function
822 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000823 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000824 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000825 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000826 TemplateArgs.getInnermost().getFlatArgumentList(),
827 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000828 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000829
830 FunctionTemplateSpecializationInfo *Info
831 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000832 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor6b906862009-08-21 00:16:32 +0000834 // If we already have a function template specialization, return it.
835 if (Info)
836 return Info->Function;
837 }
838
Douglas Gregor550d9b22009-10-31 17:21:17 +0000839 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000840
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000841 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000842 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000843 if (T.isNull())
844 return 0;
845
846 // Build the instantiated method declaration.
847 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000848 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregordec06662009-08-21 18:42:58 +0000850 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000851 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000852 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
853 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
854 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000855 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
856 Constructor->getLocation(),
857 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000858 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000859 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000860 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000861 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
862 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
863 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
864 SemaRef.Context.getCanonicalType(ClassTy));
865 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
866 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000867 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000868 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000869 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000870 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000871 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000872 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
873 ConvTy);
874 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
875 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000876 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000877 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000878 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000879 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000880 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000881 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000882 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000883 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000884
Douglas Gregord60e1052009-08-27 16:57:43 +0000885 if (TemplateParams) {
886 // Our resulting instantiation is actually a function template, since we
887 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000888 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000889 // template<typename T>
890 // struct X {
891 // template<typename U> void f(T, U);
892 // };
893 //
894 // X<int> x;
895 //
896 // We are instantiating the member template "f" within X<int>, which means
897 // substituting int for T, but leaving "f" as a member function template.
898 // Build the function template itself.
899 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
900 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000901 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000902 TemplateParams, Method);
903 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000904 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000905 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000906 } else if (FunctionTemplate) {
907 // Record this function template specialization.
908 Method->setFunctionTemplateSpecialization(SemaRef.Context,
909 FunctionTemplate,
910 &TemplateArgs.getInnermost(),
911 InsertPos);
912 } else {
913 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000914 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000915 }
916
Mike Stump1eb44332009-09-09 15:08:12 +0000917 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000918 // out-of-line, the instantiation will have the same lexical
919 // context (which will be a namespace scope) as the template.
920 if (D->isOutOfLine())
921 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor5545e162009-03-24 00:38:23 +0000923 // Attach the parameters
924 for (unsigned P = 0; P < Params.size(); ++P)
925 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000926 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000927
928 if (InitMethodInstantiation(Method, D))
929 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000930
John McCall68263142009-11-18 22:49:29 +0000931 LookupResult Previous(SemaRef, Name, SourceLocation(),
932 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregord60e1052009-08-27 16:57:43 +0000934 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000935 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregordec06662009-08-21 18:42:58 +0000937 // In C++, the previous declaration we find might be a tag type
938 // (class or enum). In this case, the new declaration will hide the
939 // tag type. Note that this does does not apply if we're declaring a
940 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000941 if (Previous.isSingleTagDecl())
942 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000943 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000944
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000945 bool Redeclaration = false;
946 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000947 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000948 /*FIXME:*/OverloadableAttrRequired);
949
Douglas Gregor4ba31362009-12-01 17:24:26 +0000950 if (D->isPure())
951 SemaRef.CheckPureMethod(Method, SourceRange());
952
John McCall68263142009-11-18 22:49:29 +0000953 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000954 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000955 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000957 return Method;
958}
959
Douglas Gregor615c5d42009-03-24 16:43:20 +0000960Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000961 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000962}
963
Douglas Gregor03b2b072009-03-24 00:15:49 +0000964Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000965 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000966}
967
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000968Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000969 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000970}
971
Douglas Gregor6477b692009-03-25 15:04:13 +0000972ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000973 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000974 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000975 if (DI) {
976 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
977 D->getDeclName());
978 if (DI) T = DI->getType();
979 } else {
980 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
981 D->getDeclName());
982 DI = 0;
983 }
984
985 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000986 return 0;
987
John McCall58e46772009-10-23 21:48:59 +0000988 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000989
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000990 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000991 ParmVarDecl *Param
992 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
993 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000994
Anders Carlsson9351c172009-08-25 03:18:48 +0000995 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000996 if (D->hasUninstantiatedDefaultArg())
997 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000998 else if (Expr *Arg = D->getDefaultArg())
999 Param->setUninstantiatedDefaultArg(Arg);
1000
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001001 // Note: we don't try to instantiate function parameters until after
1002 // we've instantiated the function's type. Therefore, we don't have
1003 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001004 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001005 return Param;
1006}
1007
John McCalle29ba202009-08-20 01:44:21 +00001008Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1009 TemplateTypeParmDecl *D) {
1010 // TODO: don't always clone when decls are refcounted.
1011 const Type* T = D->getTypeForDecl();
1012 assert(T->isTemplateTypeParmType());
1013 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001014
John McCalle29ba202009-08-20 01:44:21 +00001015 TemplateTypeParmDecl *Inst =
1016 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001017 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001018 TTPT->getName(),
1019 D->wasDeclaredWithTypename(),
1020 D->isParameterPack());
1021
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001022 if (D->hasDefaultArgument())
1023 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001024
Douglas Gregor550d9b22009-10-31 17:21:17 +00001025 // Introduce this template parameter's instantiation into the instantiation
1026 // scope.
1027 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1028
John McCalle29ba202009-08-20 01:44:21 +00001029 return Inst;
1030}
1031
Douglas Gregor33642df2009-10-23 23:25:44 +00001032Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1033 NonTypeTemplateParmDecl *D) {
1034 // Substitute into the type of the non-type template parameter.
1035 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001036 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001037 if (DI) {
1038 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1039 D->getDeclName());
1040 if (DI) T = DI->getType();
1041 } else {
1042 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1043 D->getDeclName());
1044 DI = 0;
1045 }
1046 if (T.isNull())
1047 return 0;
1048
1049 // Check that this type is acceptable for a non-type template parameter.
1050 bool Invalid = false;
1051 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1052 if (T.isNull()) {
1053 T = SemaRef.Context.IntTy;
1054 Invalid = true;
1055 }
1056
1057 NonTypeTemplateParmDecl *Param
1058 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1059 D->getDepth() - 1, D->getPosition(),
1060 D->getIdentifier(), T, DI);
1061 if (Invalid)
1062 Param->setInvalidDecl();
1063
1064 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001065
1066 // Introduce this template parameter's instantiation into the instantiation
1067 // scope.
1068 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001069 return Param;
1070}
1071
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001072Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001073TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1074 TemplateTemplateParmDecl *D) {
1075 // Instantiate the template parameter list of the template template parameter.
1076 TemplateParameterList *TempParams = D->getTemplateParameters();
1077 TemplateParameterList *InstParams;
1078 {
1079 // Perform the actual substitution of template parameters within a new,
1080 // local instantiation scope.
1081 Sema::LocalInstantiationScope Scope(SemaRef);
1082 InstParams = SubstTemplateParams(TempParams);
1083 if (!InstParams)
1084 return NULL;
1085 }
1086
1087 // Build the template template parameter.
1088 TemplateTemplateParmDecl *Param
1089 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1090 D->getDepth() - 1, D->getPosition(),
1091 D->getIdentifier(), InstParams);
1092 Param->setDefaultArgument(D->getDefaultArgument());
1093
1094 // Introduce this template parameter's instantiation into the instantiation
1095 // scope.
1096 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1097
1098 return Param;
1099}
1100
Douglas Gregor48c32a72009-11-17 06:07:40 +00001101Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1102 // Using directives are never dependent, so they require no explicit
1103
1104 UsingDirectiveDecl *Inst
1105 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1106 D->getNamespaceKeyLocation(),
1107 D->getQualifierRange(), D->getQualifier(),
1108 D->getIdentLocation(),
1109 D->getNominatedNamespace(),
1110 D->getCommonAncestor());
1111 Owner->addDecl(Inst);
1112 return Inst;
1113}
1114
John McCalled976492009-12-04 22:46:56 +00001115Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1116 // The nested name specifier is non-dependent, so no transformation
1117 // is required.
1118
John McCall9f54ad42009-12-10 09:41:52 +00001119 // We only need to do redeclaration lookups if we're in a class
1120 // scope (in fact, it's not really even possible in non-class
1121 // scopes).
1122 bool CheckRedeclaration = Owner->isRecord();
1123
1124 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1125 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1126
John McCalled976492009-12-04 22:46:56 +00001127 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1128 D->getLocation(),
1129 D->getNestedNameRange(),
1130 D->getUsingLocation(),
1131 D->getTargetNestedNameDecl(),
1132 D->getDeclName(),
1133 D->isTypeName());
1134
1135 CXXScopeSpec SS;
1136 SS.setScopeRep(D->getTargetNestedNameDecl());
1137 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001138
1139 if (CheckRedeclaration) {
1140 Prev.setHideTags(false);
1141 SemaRef.LookupQualifiedName(Prev, Owner);
1142
1143 // Check for invalid redeclarations.
1144 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1145 D->isTypeName(), SS,
1146 D->getLocation(), Prev))
1147 NewUD->setInvalidDecl();
1148
1149 }
1150
1151 if (!NewUD->isInvalidDecl() &&
1152 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001153 D->getLocation()))
1154 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001155
John McCalled976492009-12-04 22:46:56 +00001156 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1157 NewUD->setAccess(D->getAccess());
1158 Owner->addDecl(NewUD);
1159
John McCall9f54ad42009-12-10 09:41:52 +00001160 // Don't process the shadow decls for an invalid decl.
1161 if (NewUD->isInvalidDecl())
1162 return NewUD;
1163
1164 // Process the shadow decls.
1165 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1166 I != E; ++I) {
1167 UsingShadowDecl *Shadow = *I;
1168 NamedDecl *InstTarget =
1169 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1170 TemplateArgs));
1171
1172 if (CheckRedeclaration &&
1173 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1174 continue;
1175
1176 UsingShadowDecl *InstShadow
1177 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1178 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1179 }
John McCalled976492009-12-04 22:46:56 +00001180
1181 return NewUD;
1182}
1183
1184Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001185 // Ignore these; we handle them in bulk when processing the UsingDecl.
1186 return 0;
John McCalled976492009-12-04 22:46:56 +00001187}
1188
John McCall7ba107a2009-11-18 02:36:19 +00001189Decl * TemplateDeclInstantiator
1190 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001191 NestedNameSpecifier *NNS =
1192 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1193 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001194 TemplateArgs);
1195 if (!NNS)
1196 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001198 CXXScopeSpec SS;
1199 SS.setRange(D->getTargetNestedNameRange());
1200 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
1202 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001203 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001204 D->getUsingLoc(), SS, D->getLocation(),
1205 D->getDeclName(), 0,
1206 /*instantiation*/ true,
1207 /*typename*/ true, D->getTypenameLoc());
1208 if (UD)
John McCalled976492009-12-04 22:46:56 +00001209 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1210
John McCall7ba107a2009-11-18 02:36:19 +00001211 return UD;
1212}
1213
1214Decl * TemplateDeclInstantiator
1215 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1216 NestedNameSpecifier *NNS =
1217 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1218 D->getTargetNestedNameRange(),
1219 TemplateArgs);
1220 if (!NNS)
1221 return 0;
1222
1223 CXXScopeSpec SS;
1224 SS.setRange(D->getTargetNestedNameRange());
1225 SS.setScopeRep(NNS);
1226
1227 NamedDecl *UD =
1228 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1229 D->getUsingLoc(), SS, D->getLocation(),
1230 D->getDeclName(), 0,
1231 /*instantiation*/ true,
1232 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001233 if (UD)
John McCalled976492009-12-04 22:46:56 +00001234 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1235
Anders Carlsson0d8df782009-08-29 19:37:28 +00001236 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001237}
1238
John McCallce3ff2b2009-08-25 22:02:44 +00001239Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001240 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001241 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001242 return Instantiator.Visit(D);
1243}
1244
John McCalle29ba202009-08-20 01:44:21 +00001245/// \brief Instantiates a nested template parameter list in the current
1246/// instantiation context.
1247///
1248/// \param L The parameter list to instantiate
1249///
1250/// \returns NULL if there was an error
1251TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001252TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001253 // Get errors for all the parameters before bailing out.
1254 bool Invalid = false;
1255
1256 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001257 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001258 ParamVector Params;
1259 Params.reserve(N);
1260 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1261 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001262 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001263 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001264 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001265 }
1266
1267 // Clean up if we had an error.
1268 if (Invalid) {
1269 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1270 PI != PE; ++PI)
1271 if (*PI)
1272 (*PI)->Destroy(SemaRef.Context);
1273 return NULL;
1274 }
1275
1276 TemplateParameterList *InstL
1277 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1278 L->getLAngleLoc(), &Params.front(), N,
1279 L->getRAngleLoc());
1280 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001281}
John McCalle29ba202009-08-20 01:44:21 +00001282
Douglas Gregored9c0f92009-10-29 00:04:11 +00001283/// \brief Instantiate the declaration of a class template partial
1284/// specialization.
1285///
1286/// \param ClassTemplate the (instantiated) class template that is partially
1287// specialized by the instantiation of \p PartialSpec.
1288///
1289/// \param PartialSpec the (uninstantiated) class template partial
1290/// specialization that we are instantiating.
1291///
1292/// \returns true if there was an error, false otherwise.
1293bool
1294TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1295 ClassTemplateDecl *ClassTemplate,
1296 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001297 // Create a local instantiation scope for this class template partial
1298 // specialization, which will contain the instantiations of the template
1299 // parameters.
1300 Sema::LocalInstantiationScope Scope(SemaRef);
1301
Douglas Gregored9c0f92009-10-29 00:04:11 +00001302 // Substitute into the template parameters of the class template partial
1303 // specialization.
1304 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1305 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1306 if (!InstParams)
1307 return true;
1308
1309 // Substitute into the template arguments of the class template partial
1310 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001311 const TemplateArgumentLoc *PartialSpecTemplateArgs
1312 = PartialSpec->getTemplateArgsAsWritten();
1313 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1314
John McCalld5532b62009-11-23 01:53:49 +00001315 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001316 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001317 TemplateArgumentLoc Loc;
1318 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001319 return true;
John McCalld5532b62009-11-23 01:53:49 +00001320 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001321 }
1322
1323
1324 // Check that the template argument list is well-formed for this
1325 // class template.
1326 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1327 InstTemplateArgs.size());
1328 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1329 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001330 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001331 false,
1332 Converted))
1333 return true;
1334
1335 // Figure out where to insert this class template partial specialization
1336 // in the member template's set of class template partial specializations.
1337 llvm::FoldingSetNodeID ID;
1338 ClassTemplatePartialSpecializationDecl::Profile(ID,
1339 Converted.getFlatArguments(),
1340 Converted.flatSize(),
1341 SemaRef.Context);
1342 void *InsertPos = 0;
1343 ClassTemplateSpecializationDecl *PrevDecl
1344 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1345 InsertPos);
1346
1347 // Build the canonical type that describes the converted template
1348 // arguments of the class template partial specialization.
1349 QualType CanonType
1350 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1351 Converted.getFlatArguments(),
1352 Converted.flatSize());
1353
1354 // Build the fully-sugared type for this class template
1355 // specialization as the user wrote in the specialization
1356 // itself. This means that we'll pretty-print the type retrieved
1357 // from the specialization's declaration the way that the user
1358 // actually wrote the specialization, rather than formatting the
1359 // name based on the "canonical" representation used to store the
1360 // template arguments in the specialization.
1361 QualType WrittenTy
1362 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001363 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001364 CanonType);
1365
1366 if (PrevDecl) {
1367 // We've already seen a partial specialization with the same template
1368 // parameters and template arguments. This can happen, for example, when
1369 // substituting the outer template arguments ends up causing two
1370 // class template partial specializations of a member class template
1371 // to have identical forms, e.g.,
1372 //
1373 // template<typename T, typename U>
1374 // struct Outer {
1375 // template<typename X, typename Y> struct Inner;
1376 // template<typename Y> struct Inner<T, Y>;
1377 // template<typename Y> struct Inner<U, Y>;
1378 // };
1379 //
1380 // Outer<int, int> outer; // error: the partial specializations of Inner
1381 // // have the same signature.
1382 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1383 << WrittenTy;
1384 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1385 << SemaRef.Context.getTypeDeclType(PrevDecl);
1386 return true;
1387 }
1388
1389
1390 // Create the class template partial specialization declaration.
1391 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1392 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1393 PartialSpec->getLocation(),
1394 InstParams,
1395 ClassTemplate,
1396 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001397 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001398 0);
1399 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1400 InstPartialSpec->setTypeAsWritten(WrittenTy);
1401
1402 // Add this partial specialization to the set of class template partial
1403 // specializations.
1404 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1405 InsertPos);
1406 return false;
1407}
1408
John McCallce3ff2b2009-08-25 22:02:44 +00001409/// \brief Does substitution on the type of the given function, including
1410/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001411///
John McCallce3ff2b2009-08-25 22:02:44 +00001412/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001413///
1414/// \param Params the instantiated parameter declarations
1415
John McCallce3ff2b2009-08-25 22:02:44 +00001416/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001417/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001418QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001419TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001420 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1421 bool InvalidDecl = false;
1422
John McCallce3ff2b2009-08-25 22:02:44 +00001423 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001424 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001425 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001426 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001427 PEnd = D->param_end();
1428 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001429 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001430 if (PInst->getType()->isVoidType()) {
1431 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1432 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001433 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001434 PInst->getType(),
1435 diag::err_abstract_type_in_decl,
1436 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001437 PInst->setInvalidDecl();
1438
1439 Params.push_back(PInst);
1440 ParamTys.push_back(PInst->getType());
1441
1442 if (PInst->isInvalidDecl())
1443 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001444 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001445 InvalidDecl = true;
1446 }
1447
1448 // FIXME: Deallocate dead declarations.
1449 if (InvalidDecl)
1450 return QualType();
1451
John McCall183700f2009-09-21 23:43:11 +00001452 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001453 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001454 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001455 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1456 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001457 if (ResultType.isNull())
1458 return QualType();
1459
Jay Foadbeaaccd2009-05-21 09:52:38 +00001460 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001461 Proto->isVariadic(), Proto->getTypeQuals(),
1462 D->getLocation(), D->getDeclName());
1463}
1464
Mike Stump1eb44332009-09-09 15:08:12 +00001465/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001466/// declaration (New) from the corresponding fields of its template (Tmpl).
1467///
1468/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001469bool
1470TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001471 FunctionDecl *Tmpl) {
1472 if (Tmpl->isDeleted())
1473 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Douglas Gregorcca9e962009-07-01 22:01:06 +00001475 // If we are performing substituting explicitly-specified template arguments
1476 // or deduced template arguments into a function template and we reach this
1477 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001478 // to keeping the new function template specialization. We therefore
1479 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001480 // into a template instantiation for this specific function template
1481 // specialization, which is not a SFINAE context, so that we diagnose any
1482 // further errors in the declaration itself.
1483 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1484 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1485 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1486 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001487 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001488 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001489 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001490 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001491 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001492 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1493 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001494 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001495 }
1496 }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001498 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1499 assert(Proto && "Function template without prototype?");
1500
1501 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1502 Proto->getNoReturnAttr()) {
1503 // The function has an exception specification or a "noreturn"
1504 // attribute. Substitute into each of the exception types.
1505 llvm::SmallVector<QualType, 4> Exceptions;
1506 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1507 // FIXME: Poor location information!
1508 QualType T
1509 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1510 New->getLocation(), New->getDeclName());
1511 if (T.isNull() ||
1512 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1513 continue;
1514
1515 Exceptions.push_back(T);
1516 }
1517
1518 // Rebuild the function type
1519
1520 const FunctionProtoType *NewProto
1521 = New->getType()->getAs<FunctionProtoType>();
1522 assert(NewProto && "Template instantiation without function prototype?");
1523 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1524 NewProto->arg_type_begin(),
1525 NewProto->getNumArgs(),
1526 NewProto->isVariadic(),
1527 NewProto->getTypeQuals(),
1528 Proto->hasExceptionSpec(),
1529 Proto->hasAnyExceptionSpec(),
1530 Exceptions.size(),
1531 Exceptions.data(),
1532 Proto->getNoReturnAttr()));
1533 }
1534
Douglas Gregore53060f2009-06-25 22:08:12 +00001535 return false;
1536}
1537
Douglas Gregor5545e162009-03-24 00:38:23 +00001538/// \brief Initializes common fields of an instantiated method
1539/// declaration (New) from the corresponding fields of its template
1540/// (Tmpl).
1541///
1542/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001543bool
1544TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001545 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001546 if (InitFunctionInstantiation(New, Tmpl))
1547 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Douglas Gregor5545e162009-03-24 00:38:23 +00001549 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1550 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001551 if (Tmpl->isVirtualAsWritten())
1552 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001553
1554 // FIXME: attributes
1555 // FIXME: New needs a pointer to Tmpl
1556 return false;
1557}
Douglas Gregora58861f2009-05-13 20:28:22 +00001558
1559/// \brief Instantiate the definition of the given function from its
1560/// template.
1561///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001562/// \param PointOfInstantiation the point at which the instantiation was
1563/// required. Note that this is not precisely a "point of instantiation"
1564/// for the function, but it's close.
1565///
Douglas Gregora58861f2009-05-13 20:28:22 +00001566/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001567/// function template specialization or member function of a class template
1568/// specialization.
1569///
1570/// \param Recursive if true, recursively instantiates any functions that
1571/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001572///
1573/// \param DefinitionRequired if true, then we are performing an explicit
1574/// instantiation where the body of the function is required. Complain if
1575/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001576void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001577 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001578 bool Recursive,
1579 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001580 if (Function->isInvalidDecl())
1581 return;
1582
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001583 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001585 // Never instantiate an explicit specialization.
1586 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1587 return;
1588
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001589 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001590 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001591 Stmt *Pattern = 0;
1592 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001593 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001594
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001595 if (!Pattern) {
1596 if (DefinitionRequired) {
1597 if (Function->getPrimaryTemplate())
1598 Diag(PointOfInstantiation,
1599 diag::err_explicit_instantiation_undefined_func_template)
1600 << Function->getPrimaryTemplate();
1601 else
1602 Diag(PointOfInstantiation,
1603 diag::err_explicit_instantiation_undefined_member)
1604 << 1 << Function->getDeclName() << Function->getDeclContext();
1605
1606 if (PatternDecl)
1607 Diag(PatternDecl->getLocation(),
1608 diag::note_explicit_instantiation_here);
1609 }
1610
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001611 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001612 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001613
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001614 // C++0x [temp.explicit]p9:
1615 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001616 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001617 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001618 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001619 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001620 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001621 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001623 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1624 if (Inst)
1625 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001626
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001627 // If we're performing recursive template instantiation, create our own
1628 // queue of pending implicit instantiations that we will instantiate later,
1629 // while we're still within our own instantiation context.
1630 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1631 if (Recursive)
1632 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001634 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1635
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001636 // Introduce a new scope where local variable instantiations will be
1637 // recorded.
1638 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001640 // Introduce the instantiated function parameters into the local
1641 // instantiation scope.
1642 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1643 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1644 Function->getParamDecl(I));
1645
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001646 // Enter the scope of this instantiation. We don't use
1647 // PushDeclContext because we don't have a scope.
1648 DeclContext *PreviousContext = CurContext;
1649 CurContext = Function;
1650
Mike Stump1eb44332009-09-09 15:08:12 +00001651 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001652 getTemplateInstantiationArgs(Function);
1653
1654 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001655 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001656 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1657 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1658 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001659 }
1660
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001661 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001662 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001663
Douglas Gregor52604ab2009-09-11 21:19:12 +00001664 if (Body.isInvalid())
1665 Function->setInvalidDecl();
1666
Mike Stump1eb44332009-09-09 15:08:12 +00001667 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001668 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001669
1670 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001671
1672 DeclGroupRef DG(Function);
1673 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001675 if (Recursive) {
1676 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001677 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001678 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001680 // Restore the set of pending implicit instantiations.
1681 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1682 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001683}
1684
1685/// \brief Instantiate the definition of the given variable from its
1686/// template.
1687///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001688/// \param PointOfInstantiation the point at which the instantiation was
1689/// required. Note that this is not precisely a "point of instantiation"
1690/// for the function, but it's close.
1691///
1692/// \param Var the already-instantiated declaration of a static member
1693/// variable of a class template specialization.
1694///
1695/// \param Recursive if true, recursively instantiates any functions that
1696/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001697///
1698/// \param DefinitionRequired if true, then we are performing an explicit
1699/// instantiation where an out-of-line definition of the member variable
1700/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001701void Sema::InstantiateStaticDataMemberDefinition(
1702 SourceLocation PointOfInstantiation,
1703 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001704 bool Recursive,
1705 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001706 if (Var->isInvalidDecl())
1707 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor7caa6822009-07-24 20:34:43 +00001709 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001710 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001711 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001712 assert(Def->isStaticDataMember() && "Not a static data member?");
1713 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor0d035142009-10-27 18:42:08 +00001715 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001716 // We did not find an out-of-line definition of this static data member,
1717 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // instantiate this definition (or provide a specialization for it) in
1719 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001720 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001721 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001722 Diag(PointOfInstantiation,
1723 diag::err_explicit_instantiation_undefined_member)
1724 << 2 << Var->getDeclName() << Var->getDeclContext();
1725 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1726 }
1727
Douglas Gregor7caa6822009-07-24 20:34:43 +00001728 return;
1729 }
1730
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001731 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001732 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001733 return;
1734
1735 // C++0x [temp.explicit]p9:
1736 // Except for inline functions, other explicit instantiation declarations
1737 // have the effect of suppressing the implicit instantiation of the entity
1738 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001739 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001740 == TSK_ExplicitInstantiationDeclaration)
1741 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Douglas Gregor7caa6822009-07-24 20:34:43 +00001743 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1744 if (Inst)
1745 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor7caa6822009-07-24 20:34:43 +00001747 // If we're performing recursive template instantiation, create our own
1748 // queue of pending implicit instantiations that we will instantiate later,
1749 // while we're still within our own instantiation context.
1750 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1751 if (Recursive)
1752 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Douglas Gregor7caa6822009-07-24 20:34:43 +00001754 // Enter the scope of this instantiation. We don't use
1755 // PushDeclContext because we don't have a scope.
1756 DeclContext *PreviousContext = CurContext;
1757 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001759 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001760 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001761 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001762 CurContext = PreviousContext;
1763
1764 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001765 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001766 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1767 assert(MSInfo && "Missing member specialization information?");
1768 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1769 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001770 DeclGroupRef DG(Var);
1771 Consumer.HandleTopLevelDecl(DG);
1772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregor7caa6822009-07-24 20:34:43 +00001774 if (Recursive) {
1775 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001776 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001777 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregor7caa6822009-07-24 20:34:43 +00001779 // Restore the set of pending implicit instantiations.
1780 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001781 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001782}
Douglas Gregor815215d2009-05-27 05:35:12 +00001783
Anders Carlsson09025312009-08-29 05:16:22 +00001784void
1785Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1786 const CXXConstructorDecl *Tmpl,
1787 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Anders Carlsson09025312009-08-29 05:16:22 +00001789 llvm::SmallVector<MemInitTy*, 4> NewInits;
1790
1791 // Instantiate all the initializers.
1792 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001793 InitsEnd = Tmpl->init_end();
1794 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001795 CXXBaseOrMemberInitializer *Init = *Inits;
1796
1797 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlsson09025312009-08-29 05:16:22 +00001799 // Instantiate all the arguments.
1800 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1801 Args != ArgsEnd; ++Args) {
1802 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1803
1804 if (NewArg.isInvalid())
1805 New->setInvalidDecl();
1806 else
1807 NewArgs.push_back(NewArg.takeAs<Expr>());
1808 }
1809
1810 MemInitResult NewInit;
1811
1812 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001813 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001814 TemplateArgs,
1815 Init->getSourceLocation(),
1816 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001817 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001818 New->setInvalidDecl();
1819 continue;
1820 }
1821
John McCalla93c9342009-12-07 02:54:59 +00001822 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001823 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001824 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001825 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001826 Init->getRParenLoc(),
1827 New->getParent());
1828 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001829 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001831 // Is this an anonymous union?
1832 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001833 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001834 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001835 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1836 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001837
1838 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001839 NewArgs.size(),
1840 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001841 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001842 Init->getRParenLoc());
1843 }
1844
1845 if (NewInit.isInvalid())
1846 New->setInvalidDecl();
1847 else {
1848 // FIXME: It would be nice if ASTOwningVector had a release function.
1849 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Anders Carlsson09025312009-08-29 05:16:22 +00001851 NewInits.push_back((MemInitTy *)NewInit.get());
1852 }
1853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Anders Carlsson09025312009-08-29 05:16:22 +00001855 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001856 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001857 /*FIXME: ColonLoc */
1858 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001859 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001860}
1861
John McCall52a575a2009-08-29 08:11:13 +00001862// TODO: this could be templated if the various decl types used the
1863// same method name.
1864static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1865 ClassTemplateDecl *Instance) {
1866 Pattern = Pattern->getCanonicalDecl();
1867
1868 do {
1869 Instance = Instance->getCanonicalDecl();
1870 if (Pattern == Instance) return true;
1871 Instance = Instance->getInstantiatedFromMemberTemplate();
1872 } while (Instance);
1873
1874 return false;
1875}
1876
Douglas Gregor0d696532009-09-28 06:34:35 +00001877static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1878 FunctionTemplateDecl *Instance) {
1879 Pattern = Pattern->getCanonicalDecl();
1880
1881 do {
1882 Instance = Instance->getCanonicalDecl();
1883 if (Pattern == Instance) return true;
1884 Instance = Instance->getInstantiatedFromMemberTemplate();
1885 } while (Instance);
1886
1887 return false;
1888}
1889
Douglas Gregored9c0f92009-10-29 00:04:11 +00001890static bool
1891isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1892 ClassTemplatePartialSpecializationDecl *Instance) {
1893 Pattern
1894 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1895 do {
1896 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1897 Instance->getCanonicalDecl());
1898 if (Pattern == Instance)
1899 return true;
1900 Instance = Instance->getInstantiatedFromMember();
1901 } while (Instance);
1902
1903 return false;
1904}
1905
John McCall52a575a2009-08-29 08:11:13 +00001906static bool isInstantiationOf(CXXRecordDecl *Pattern,
1907 CXXRecordDecl *Instance) {
1908 Pattern = Pattern->getCanonicalDecl();
1909
1910 do {
1911 Instance = Instance->getCanonicalDecl();
1912 if (Pattern == Instance) return true;
1913 Instance = Instance->getInstantiatedFromMemberClass();
1914 } while (Instance);
1915
1916 return false;
1917}
1918
1919static bool isInstantiationOf(FunctionDecl *Pattern,
1920 FunctionDecl *Instance) {
1921 Pattern = Pattern->getCanonicalDecl();
1922
1923 do {
1924 Instance = Instance->getCanonicalDecl();
1925 if (Pattern == Instance) return true;
1926 Instance = Instance->getInstantiatedFromMemberFunction();
1927 } while (Instance);
1928
1929 return false;
1930}
1931
1932static bool isInstantiationOf(EnumDecl *Pattern,
1933 EnumDecl *Instance) {
1934 Pattern = Pattern->getCanonicalDecl();
1935
1936 do {
1937 Instance = Instance->getCanonicalDecl();
1938 if (Pattern == Instance) return true;
1939 Instance = Instance->getInstantiatedFromMemberEnum();
1940 } while (Instance);
1941
1942 return false;
1943}
1944
John McCalled976492009-12-04 22:46:56 +00001945static bool isInstantiationOf(UsingShadowDecl *Pattern,
1946 UsingShadowDecl *Instance,
1947 ASTContext &C) {
1948 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1949}
1950
1951static bool isInstantiationOf(UsingDecl *Pattern,
1952 UsingDecl *Instance,
1953 ASTContext &C) {
1954 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1955}
1956
John McCall7ba107a2009-11-18 02:36:19 +00001957static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1958 UsingDecl *Instance,
1959 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001960 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001961}
1962
1963static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001964 UsingDecl *Instance,
1965 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001966 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001967}
1968
John McCall52a575a2009-08-29 08:11:13 +00001969static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1970 VarDecl *Instance) {
1971 assert(Instance->isStaticDataMember());
1972
1973 Pattern = Pattern->getCanonicalDecl();
1974
1975 do {
1976 Instance = Instance->getCanonicalDecl();
1977 if (Pattern == Instance) return true;
1978 Instance = Instance->getInstantiatedFromStaticDataMember();
1979 } while (Instance);
1980
1981 return false;
1982}
1983
John McCalled976492009-12-04 22:46:56 +00001984// Other is the prospective instantiation
1985// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001986static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001987 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001988 if (UnresolvedUsingTypenameDecl *UUD
1989 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1990 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1991 return isInstantiationOf(UUD, UD, Ctx);
1992 }
1993 }
1994
1995 if (UnresolvedUsingValueDecl *UUD
1996 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001997 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1998 return isInstantiationOf(UUD, UD, Ctx);
1999 }
2000 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002001
Anders Carlsson0d8df782009-08-29 19:37:28 +00002002 return false;
2003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
John McCall52a575a2009-08-29 08:11:13 +00002005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2006 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002007
John McCall52a575a2009-08-29 08:11:13 +00002008 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2009 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002010
John McCall52a575a2009-08-29 08:11:13 +00002011 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2012 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002013
Douglas Gregor7caa6822009-07-24 20:34:43 +00002014 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002015 if (Var->isStaticDataMember())
2016 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2017
2018 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2019 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002020
Douglas Gregor0d696532009-09-28 06:34:35 +00002021 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2022 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2023
Douglas Gregored9c0f92009-10-29 00:04:11 +00002024 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2025 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2026 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2027 PartialSpec);
2028
Anders Carlssond8b285f2009-09-01 04:26:58 +00002029 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2030 if (!Field->getDeclName()) {
2031 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002033 cast<FieldDecl>(D);
2034 }
2035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
John McCalled976492009-12-04 22:46:56 +00002037 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2038 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2039
2040 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2041 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2042
Douglas Gregor815215d2009-05-27 05:35:12 +00002043 return D->getDeclName() && isa<NamedDecl>(Other) &&
2044 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2045}
2046
2047template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002048static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002049 NamedDecl *D,
2050 ForwardIterator first,
2051 ForwardIterator last) {
2052 for (; first != last; ++first)
2053 if (isInstantiationOf(Ctx, D, *first))
2054 return cast<NamedDecl>(*first);
2055
2056 return 0;
2057}
2058
John McCall02cace72009-08-28 07:59:38 +00002059/// \brief Finds the instantiation of the given declaration context
2060/// within the current instantiation.
2061///
2062/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002063DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2064 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002065 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002066 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002067 return cast_or_null<DeclContext>(ID);
2068 } else return DC;
2069}
2070
Douglas Gregored961e72009-05-27 17:54:46 +00002071/// \brief Find the instantiation of the given declaration within the
2072/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002073///
2074/// This routine is intended to be used when \p D is a declaration
2075/// referenced from within a template, that needs to mapped into the
2076/// corresponding declaration within an instantiation. For example,
2077/// given:
2078///
2079/// \code
2080/// template<typename T>
2081/// struct X {
2082/// enum Kind {
2083/// KnownValue = sizeof(T)
2084/// };
2085///
2086/// bool getKind() const { return KnownValue; }
2087/// };
2088///
2089/// template struct X<int>;
2090/// \endcode
2091///
2092/// In the instantiation of X<int>::getKind(), we need to map the
2093/// EnumConstantDecl for KnownValue (which refers to
2094/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002095/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2096/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002097NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2098 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002099 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002100 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2101 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2102 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002103 // D is a local of some kind. Look into the map of local
2104 // declarations to their instantiations.
2105 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2106 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002107
Douglas Gregore95b4092009-09-16 18:34:49 +00002108 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2109 if (!Record->isDependentContext())
2110 return D;
2111
2112 // If the RecordDecl is actually the injected-class-name or a "templated"
2113 // declaration for a class template or class template partial
2114 // specialization, substitute into the injected-class-name of the
2115 // class template or partial specialization to find the new DeclContext.
2116 QualType T;
2117 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2118
2119 if (ClassTemplate) {
2120 T = ClassTemplate->getInjectedClassNameType(Context);
2121 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2122 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2123 T = Context.getTypeDeclType(Record);
2124 ClassTemplate = PartialSpec->getSpecializedTemplate();
2125 }
2126
2127 if (!T.isNull()) {
2128 // Substitute into the injected-class-name to get the type corresponding
2129 // to the instantiation we want. This substitution should never fail,
2130 // since we know we can instantiate the injected-class-name or we wouldn't
2131 // have gotten to the injected-class-name!
2132 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2133 // instantiation in the common case?
2134 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2135 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2136
2137 if (!T->isDependentType()) {
2138 assert(T->isRecordType() && "Instantiation must produce a record type");
2139 return T->getAs<RecordType>()->getDecl();
2140 }
2141
2142 // We are performing "partial" template instantiation to create the
2143 // member declarations for the members of a class template
2144 // specialization. Therefore, D is actually referring to something in
2145 // the current instantiation. Look through the current context,
2146 // which contains actual instantiations, to find the instantiation of
2147 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002148 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002149 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002150 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002151 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002152 if (isInstantiationOf(ClassTemplate,
2153 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002154 return Spec;
2155 }
2156
Mike Stump1eb44332009-09-09 15:08:12 +00002157 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002158 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002159 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002160 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002161
2162 // Fall through to deal with other dependent record types (e.g.,
2163 // anonymous unions in class templates).
2164 }
John McCall52a575a2009-08-29 08:11:13 +00002165
Douglas Gregore95b4092009-09-16 18:34:49 +00002166 if (!ParentDC->isDependentContext())
2167 return D;
2168
2169 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002170 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002171 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregor815215d2009-05-27 05:35:12 +00002173 if (ParentDC != D->getDeclContext()) {
2174 // We performed some kind of instantiation in the parent context,
2175 // so now we need to look into the instantiated parent context to
2176 // find the instantiation of the declaration D.
2177 NamedDecl *Result = 0;
2178 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002179 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002180 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2181 } else {
2182 // Since we don't have a name for the entity we're looking for,
2183 // our only option is to walk through all of the declarations to
2184 // find that name. This will occur in a few cases:
2185 //
2186 // - anonymous struct/union within a template
2187 // - unnamed class/struct/union/enum within a template
2188 //
2189 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002190 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002191 ParentDC->decls_begin(),
2192 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002193 }
Mike Stump1eb44332009-09-09 15:08:12 +00002194
John McCall9f54ad42009-12-10 09:41:52 +00002195 // UsingShadowDecls can instantiate to nothing because of using hiding.
2196 assert((Result || isa<UsingShadowDecl>(D))
2197 && "Unable to find instantiation of declaration!");
2198
Douglas Gregor815215d2009-05-27 05:35:12 +00002199 D = Result;
2200 }
2201
Douglas Gregor815215d2009-05-27 05:35:12 +00002202 return D;
2203}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002204
Mike Stump1eb44332009-09-09 15:08:12 +00002205/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002206/// instantiations we have seen until this point.
2207void Sema::PerformPendingImplicitInstantiations() {
2208 while (!PendingImplicitInstantiations.empty()) {
2209 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002210 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor7caa6822009-07-24 20:34:43 +00002212 // Instantiate function definitions
2213 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002214 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002215 Function->getLocation(), *this,
2216 Context.getSourceManager(),
2217 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002219 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002220 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002221 continue;
2222 }
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregor7caa6822009-07-24 20:34:43 +00002224 // Instantiate static data member definitions.
2225 VarDecl *Var = cast<VarDecl>(Inst.first);
2226 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002227
Mike Stump1eb44332009-09-09 15:08:12 +00002228 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002229 Var->getLocation(), *this,
2230 Context.getSourceManager(),
2231 "instantiating static data member "
2232 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregor7caa6822009-07-24 20:34:43 +00002234 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002235 }
2236}