blob: 18a73250a529d0f768edf44052201eb34826c4cc [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
John McCall323c3102009-12-22 22:26:37 +00001164 bool isFunctionScope = Owner->isFunctionOrMethod();
1165
John McCall9f54ad42009-12-10 09:41:52 +00001166 // Process the shadow decls.
1167 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1168 I != E; ++I) {
1169 UsingShadowDecl *Shadow = *I;
1170 NamedDecl *InstTarget =
1171 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1172 TemplateArgs));
1173
1174 if (CheckRedeclaration &&
1175 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1176 continue;
1177
1178 UsingShadowDecl *InstShadow
1179 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1180 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001181
1182 if (isFunctionScope)
1183 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001184 }
John McCalled976492009-12-04 22:46:56 +00001185
1186 return NewUD;
1187}
1188
1189Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001190 // Ignore these; we handle them in bulk when processing the UsingDecl.
1191 return 0;
John McCalled976492009-12-04 22:46:56 +00001192}
1193
John McCall7ba107a2009-11-18 02:36:19 +00001194Decl * TemplateDeclInstantiator
1195 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001196 NestedNameSpecifier *NNS =
1197 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1198 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001199 TemplateArgs);
1200 if (!NNS)
1201 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001203 CXXScopeSpec SS;
1204 SS.setRange(D->getTargetNestedNameRange());
1205 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
1207 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001208 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001209 D->getUsingLoc(), SS, D->getLocation(),
1210 D->getDeclName(), 0,
1211 /*instantiation*/ true,
1212 /*typename*/ true, D->getTypenameLoc());
1213 if (UD)
John McCalled976492009-12-04 22:46:56 +00001214 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1215
John McCall7ba107a2009-11-18 02:36:19 +00001216 return UD;
1217}
1218
1219Decl * TemplateDeclInstantiator
1220 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1221 NestedNameSpecifier *NNS =
1222 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1223 D->getTargetNestedNameRange(),
1224 TemplateArgs);
1225 if (!NNS)
1226 return 0;
1227
1228 CXXScopeSpec SS;
1229 SS.setRange(D->getTargetNestedNameRange());
1230 SS.setScopeRep(NNS);
1231
1232 NamedDecl *UD =
1233 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1234 D->getUsingLoc(), SS, D->getLocation(),
1235 D->getDeclName(), 0,
1236 /*instantiation*/ true,
1237 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001238 if (UD)
John McCalled976492009-12-04 22:46:56 +00001239 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1240
Anders Carlsson0d8df782009-08-29 19:37:28 +00001241 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001242}
1243
John McCallce3ff2b2009-08-25 22:02:44 +00001244Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001245 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001246 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001247 return Instantiator.Visit(D);
1248}
1249
John McCalle29ba202009-08-20 01:44:21 +00001250/// \brief Instantiates a nested template parameter list in the current
1251/// instantiation context.
1252///
1253/// \param L The parameter list to instantiate
1254///
1255/// \returns NULL if there was an error
1256TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001257TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001258 // Get errors for all the parameters before bailing out.
1259 bool Invalid = false;
1260
1261 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001262 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001263 ParamVector Params;
1264 Params.reserve(N);
1265 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1266 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001267 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001268 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001269 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001270 }
1271
1272 // Clean up if we had an error.
1273 if (Invalid) {
1274 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1275 PI != PE; ++PI)
1276 if (*PI)
1277 (*PI)->Destroy(SemaRef.Context);
1278 return NULL;
1279 }
1280
1281 TemplateParameterList *InstL
1282 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1283 L->getLAngleLoc(), &Params.front(), N,
1284 L->getRAngleLoc());
1285 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001286}
John McCalle29ba202009-08-20 01:44:21 +00001287
Douglas Gregored9c0f92009-10-29 00:04:11 +00001288/// \brief Instantiate the declaration of a class template partial
1289/// specialization.
1290///
1291/// \param ClassTemplate the (instantiated) class template that is partially
1292// specialized by the instantiation of \p PartialSpec.
1293///
1294/// \param PartialSpec the (uninstantiated) class template partial
1295/// specialization that we are instantiating.
1296///
1297/// \returns true if there was an error, false otherwise.
1298bool
1299TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1300 ClassTemplateDecl *ClassTemplate,
1301 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001302 // Create a local instantiation scope for this class template partial
1303 // specialization, which will contain the instantiations of the template
1304 // parameters.
1305 Sema::LocalInstantiationScope Scope(SemaRef);
1306
Douglas Gregored9c0f92009-10-29 00:04:11 +00001307 // Substitute into the template parameters of the class template partial
1308 // specialization.
1309 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1310 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1311 if (!InstParams)
1312 return true;
1313
1314 // Substitute into the template arguments of the class template partial
1315 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001316 const TemplateArgumentLoc *PartialSpecTemplateArgs
1317 = PartialSpec->getTemplateArgsAsWritten();
1318 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1319
John McCalld5532b62009-11-23 01:53:49 +00001320 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001321 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001322 TemplateArgumentLoc Loc;
1323 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001324 return true;
John McCalld5532b62009-11-23 01:53:49 +00001325 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001326 }
1327
1328
1329 // Check that the template argument list is well-formed for this
1330 // class template.
1331 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1332 InstTemplateArgs.size());
1333 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1334 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001335 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001336 false,
1337 Converted))
1338 return true;
1339
1340 // Figure out where to insert this class template partial specialization
1341 // in the member template's set of class template partial specializations.
1342 llvm::FoldingSetNodeID ID;
1343 ClassTemplatePartialSpecializationDecl::Profile(ID,
1344 Converted.getFlatArguments(),
1345 Converted.flatSize(),
1346 SemaRef.Context);
1347 void *InsertPos = 0;
1348 ClassTemplateSpecializationDecl *PrevDecl
1349 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1350 InsertPos);
1351
1352 // Build the canonical type that describes the converted template
1353 // arguments of the class template partial specialization.
1354 QualType CanonType
1355 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1356 Converted.getFlatArguments(),
1357 Converted.flatSize());
1358
1359 // Build the fully-sugared type for this class template
1360 // specialization as the user wrote in the specialization
1361 // itself. This means that we'll pretty-print the type retrieved
1362 // from the specialization's declaration the way that the user
1363 // actually wrote the specialization, rather than formatting the
1364 // name based on the "canonical" representation used to store the
1365 // template arguments in the specialization.
1366 QualType WrittenTy
1367 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001368 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001369 CanonType);
1370
1371 if (PrevDecl) {
1372 // We've already seen a partial specialization with the same template
1373 // parameters and template arguments. This can happen, for example, when
1374 // substituting the outer template arguments ends up causing two
1375 // class template partial specializations of a member class template
1376 // to have identical forms, e.g.,
1377 //
1378 // template<typename T, typename U>
1379 // struct Outer {
1380 // template<typename X, typename Y> struct Inner;
1381 // template<typename Y> struct Inner<T, Y>;
1382 // template<typename Y> struct Inner<U, Y>;
1383 // };
1384 //
1385 // Outer<int, int> outer; // error: the partial specializations of Inner
1386 // // have the same signature.
1387 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1388 << WrittenTy;
1389 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1390 << SemaRef.Context.getTypeDeclType(PrevDecl);
1391 return true;
1392 }
1393
1394
1395 // Create the class template partial specialization declaration.
1396 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1397 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1398 PartialSpec->getLocation(),
1399 InstParams,
1400 ClassTemplate,
1401 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001402 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001403 0);
1404 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1405 InstPartialSpec->setTypeAsWritten(WrittenTy);
1406
1407 // Add this partial specialization to the set of class template partial
1408 // specializations.
1409 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1410 InsertPos);
1411 return false;
1412}
1413
John McCallce3ff2b2009-08-25 22:02:44 +00001414/// \brief Does substitution on the type of the given function, including
1415/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001416///
John McCallce3ff2b2009-08-25 22:02:44 +00001417/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001418///
1419/// \param Params the instantiated parameter declarations
1420
John McCallce3ff2b2009-08-25 22:02:44 +00001421/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001422/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001423QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001424TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001425 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1426 bool InvalidDecl = false;
1427
John McCallce3ff2b2009-08-25 22:02:44 +00001428 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001429 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001430 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001431 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001432 PEnd = D->param_end();
1433 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001434 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001435 if (PInst->getType()->isVoidType()) {
1436 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1437 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001438 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001439 PInst->getType(),
1440 diag::err_abstract_type_in_decl,
1441 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001442 PInst->setInvalidDecl();
1443
1444 Params.push_back(PInst);
1445 ParamTys.push_back(PInst->getType());
1446
1447 if (PInst->isInvalidDecl())
1448 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001449 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001450 InvalidDecl = true;
1451 }
1452
1453 // FIXME: Deallocate dead declarations.
1454 if (InvalidDecl)
1455 return QualType();
1456
John McCall183700f2009-09-21 23:43:11 +00001457 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001458 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001459 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001460 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1461 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001462 if (ResultType.isNull())
1463 return QualType();
1464
Jay Foadbeaaccd2009-05-21 09:52:38 +00001465 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001466 Proto->isVariadic(), Proto->getTypeQuals(),
1467 D->getLocation(), D->getDeclName());
1468}
1469
Mike Stump1eb44332009-09-09 15:08:12 +00001470/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001471/// declaration (New) from the corresponding fields of its template (Tmpl).
1472///
1473/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001474bool
1475TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001476 FunctionDecl *Tmpl) {
1477 if (Tmpl->isDeleted())
1478 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Douglas Gregorcca9e962009-07-01 22:01:06 +00001480 // If we are performing substituting explicitly-specified template arguments
1481 // or deduced template arguments into a function template and we reach this
1482 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001483 // to keeping the new function template specialization. We therefore
1484 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001485 // into a template instantiation for this specific function template
1486 // specialization, which is not a SFINAE context, so that we diagnose any
1487 // further errors in the declaration itself.
1488 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1489 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1490 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1491 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001492 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001493 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001494 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001495 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001496 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001497 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1498 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001499 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001500 }
1501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001503 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1504 assert(Proto && "Function template without prototype?");
1505
1506 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1507 Proto->getNoReturnAttr()) {
1508 // The function has an exception specification or a "noreturn"
1509 // attribute. Substitute into each of the exception types.
1510 llvm::SmallVector<QualType, 4> Exceptions;
1511 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1512 // FIXME: Poor location information!
1513 QualType T
1514 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1515 New->getLocation(), New->getDeclName());
1516 if (T.isNull() ||
1517 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1518 continue;
1519
1520 Exceptions.push_back(T);
1521 }
1522
1523 // Rebuild the function type
1524
1525 const FunctionProtoType *NewProto
1526 = New->getType()->getAs<FunctionProtoType>();
1527 assert(NewProto && "Template instantiation without function prototype?");
1528 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1529 NewProto->arg_type_begin(),
1530 NewProto->getNumArgs(),
1531 NewProto->isVariadic(),
1532 NewProto->getTypeQuals(),
1533 Proto->hasExceptionSpec(),
1534 Proto->hasAnyExceptionSpec(),
1535 Exceptions.size(),
1536 Exceptions.data(),
1537 Proto->getNoReturnAttr()));
1538 }
1539
Douglas Gregore53060f2009-06-25 22:08:12 +00001540 return false;
1541}
1542
Douglas Gregor5545e162009-03-24 00:38:23 +00001543/// \brief Initializes common fields of an instantiated method
1544/// declaration (New) from the corresponding fields of its template
1545/// (Tmpl).
1546///
1547/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001548bool
1549TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001550 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001551 if (InitFunctionInstantiation(New, Tmpl))
1552 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Douglas Gregor5545e162009-03-24 00:38:23 +00001554 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1555 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001556 if (Tmpl->isVirtualAsWritten())
1557 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001558
1559 // FIXME: attributes
1560 // FIXME: New needs a pointer to Tmpl
1561 return false;
1562}
Douglas Gregora58861f2009-05-13 20:28:22 +00001563
1564/// \brief Instantiate the definition of the given function from its
1565/// template.
1566///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001567/// \param PointOfInstantiation the point at which the instantiation was
1568/// required. Note that this is not precisely a "point of instantiation"
1569/// for the function, but it's close.
1570///
Douglas Gregora58861f2009-05-13 20:28:22 +00001571/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001572/// function template specialization or member function of a class template
1573/// specialization.
1574///
1575/// \param Recursive if true, recursively instantiates any functions that
1576/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001577///
1578/// \param DefinitionRequired if true, then we are performing an explicit
1579/// instantiation where the body of the function is required. Complain if
1580/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001581void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001582 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001583 bool Recursive,
1584 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001585 if (Function->isInvalidDecl())
1586 return;
1587
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001588 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001590 // Never instantiate an explicit specialization.
1591 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592 return;
1593
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001594 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001595 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001596 Stmt *Pattern = 0;
1597 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001598 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001599
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001600 if (!Pattern) {
1601 if (DefinitionRequired) {
1602 if (Function->getPrimaryTemplate())
1603 Diag(PointOfInstantiation,
1604 diag::err_explicit_instantiation_undefined_func_template)
1605 << Function->getPrimaryTemplate();
1606 else
1607 Diag(PointOfInstantiation,
1608 diag::err_explicit_instantiation_undefined_member)
1609 << 1 << Function->getDeclName() << Function->getDeclContext();
1610
1611 if (PatternDecl)
1612 Diag(PatternDecl->getLocation(),
1613 diag::note_explicit_instantiation_here);
1614 }
1615
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001616 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001617 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001618
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001619 // C++0x [temp.explicit]p9:
1620 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001621 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001622 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001623 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001624 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001625 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001626 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001628 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1629 if (Inst)
1630 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001631
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001632 // If we're performing recursive template instantiation, create our own
1633 // queue of pending implicit instantiations that we will instantiate later,
1634 // while we're still within our own instantiation context.
1635 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1636 if (Recursive)
1637 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001639 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1640
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001641 // Introduce a new scope where local variable instantiations will be
1642 // recorded.
1643 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001645 // Introduce the instantiated function parameters into the local
1646 // instantiation scope.
1647 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1648 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1649 Function->getParamDecl(I));
1650
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001651 // Enter the scope of this instantiation. We don't use
1652 // PushDeclContext because we don't have a scope.
1653 DeclContext *PreviousContext = CurContext;
1654 CurContext = Function;
1655
Mike Stump1eb44332009-09-09 15:08:12 +00001656 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001657 getTemplateInstantiationArgs(Function);
1658
1659 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001660 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001661 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1662 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1663 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001664 }
1665
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001666 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001667 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001668
Douglas Gregor52604ab2009-09-11 21:19:12 +00001669 if (Body.isInvalid())
1670 Function->setInvalidDecl();
1671
Mike Stump1eb44332009-09-09 15:08:12 +00001672 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001673 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001674
1675 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001676
1677 DeclGroupRef DG(Function);
1678 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001680 if (Recursive) {
1681 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001682 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001683 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001685 // Restore the set of pending implicit instantiations.
1686 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1687 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001688}
1689
1690/// \brief Instantiate the definition of the given variable from its
1691/// template.
1692///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001693/// \param PointOfInstantiation the point at which the instantiation was
1694/// required. Note that this is not precisely a "point of instantiation"
1695/// for the function, but it's close.
1696///
1697/// \param Var the already-instantiated declaration of a static member
1698/// variable of a class template specialization.
1699///
1700/// \param Recursive if true, recursively instantiates any functions that
1701/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001702///
1703/// \param DefinitionRequired if true, then we are performing an explicit
1704/// instantiation where an out-of-line definition of the member variable
1705/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001706void Sema::InstantiateStaticDataMemberDefinition(
1707 SourceLocation PointOfInstantiation,
1708 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001709 bool Recursive,
1710 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001711 if (Var->isInvalidDecl())
1712 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregor7caa6822009-07-24 20:34:43 +00001714 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001715 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001716 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001717 assert(Def->isStaticDataMember() && "Not a static data member?");
1718 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Douglas Gregor0d035142009-10-27 18:42:08 +00001720 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001721 // We did not find an out-of-line definition of this static data member,
1722 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // instantiate this definition (or provide a specialization for it) in
1724 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001725 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001726 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001727 Diag(PointOfInstantiation,
1728 diag::err_explicit_instantiation_undefined_member)
1729 << 2 << Var->getDeclName() << Var->getDeclContext();
1730 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1731 }
1732
Douglas Gregor7caa6822009-07-24 20:34:43 +00001733 return;
1734 }
1735
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001736 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001737 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001738 return;
1739
1740 // C++0x [temp.explicit]p9:
1741 // Except for inline functions, other explicit instantiation declarations
1742 // have the effect of suppressing the implicit instantiation of the entity
1743 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001744 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001745 == TSK_ExplicitInstantiationDeclaration)
1746 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Douglas Gregor7caa6822009-07-24 20:34:43 +00001748 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1749 if (Inst)
1750 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregor7caa6822009-07-24 20:34:43 +00001752 // If we're performing recursive template instantiation, create our own
1753 // queue of pending implicit instantiations that we will instantiate later,
1754 // while we're still within our own instantiation context.
1755 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1756 if (Recursive)
1757 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Douglas Gregor7caa6822009-07-24 20:34:43 +00001759 // Enter the scope of this instantiation. We don't use
1760 // PushDeclContext because we don't have a scope.
1761 DeclContext *PreviousContext = CurContext;
1762 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001764 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001765 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001766 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001767 CurContext = PreviousContext;
1768
1769 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001770 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001771 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1772 assert(MSInfo && "Missing member specialization information?");
1773 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1774 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001775 DeclGroupRef DG(Var);
1776 Consumer.HandleTopLevelDecl(DG);
1777 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregor7caa6822009-07-24 20:34:43 +00001779 if (Recursive) {
1780 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001781 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001782 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregor7caa6822009-07-24 20:34:43 +00001784 // Restore the set of pending implicit instantiations.
1785 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001786 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001787}
Douglas Gregor815215d2009-05-27 05:35:12 +00001788
Anders Carlsson09025312009-08-29 05:16:22 +00001789void
1790Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1791 const CXXConstructorDecl *Tmpl,
1792 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlsson09025312009-08-29 05:16:22 +00001794 llvm::SmallVector<MemInitTy*, 4> NewInits;
1795
1796 // Instantiate all the initializers.
1797 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001798 InitsEnd = Tmpl->init_end();
1799 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001800 CXXBaseOrMemberInitializer *Init = *Inits;
1801
1802 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Anders Carlsson09025312009-08-29 05:16:22 +00001804 // Instantiate all the arguments.
1805 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1806 Args != ArgsEnd; ++Args) {
1807 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1808
1809 if (NewArg.isInvalid())
1810 New->setInvalidDecl();
1811 else
1812 NewArgs.push_back(NewArg.takeAs<Expr>());
1813 }
1814
1815 MemInitResult NewInit;
1816
1817 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001818 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001819 TemplateArgs,
1820 Init->getSourceLocation(),
1821 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001822 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001823 New->setInvalidDecl();
1824 continue;
1825 }
1826
John McCalla93c9342009-12-07 02:54:59 +00001827 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001828 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001829 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001830 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001831 Init->getRParenLoc(),
1832 New->getParent());
1833 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001834 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001836 // Is this an anonymous union?
1837 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001838 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001839 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001840 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1841 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001842
1843 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001844 NewArgs.size(),
1845 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001846 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001847 Init->getRParenLoc());
1848 }
1849
1850 if (NewInit.isInvalid())
1851 New->setInvalidDecl();
1852 else {
1853 // FIXME: It would be nice if ASTOwningVector had a release function.
1854 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Anders Carlsson09025312009-08-29 05:16:22 +00001856 NewInits.push_back((MemInitTy *)NewInit.get());
1857 }
1858 }
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Anders Carlsson09025312009-08-29 05:16:22 +00001860 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001861 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001862 /*FIXME: ColonLoc */
1863 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001864 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001865}
1866
John McCall52a575a2009-08-29 08:11:13 +00001867// TODO: this could be templated if the various decl types used the
1868// same method name.
1869static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1870 ClassTemplateDecl *Instance) {
1871 Pattern = Pattern->getCanonicalDecl();
1872
1873 do {
1874 Instance = Instance->getCanonicalDecl();
1875 if (Pattern == Instance) return true;
1876 Instance = Instance->getInstantiatedFromMemberTemplate();
1877 } while (Instance);
1878
1879 return false;
1880}
1881
Douglas Gregor0d696532009-09-28 06:34:35 +00001882static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1883 FunctionTemplateDecl *Instance) {
1884 Pattern = Pattern->getCanonicalDecl();
1885
1886 do {
1887 Instance = Instance->getCanonicalDecl();
1888 if (Pattern == Instance) return true;
1889 Instance = Instance->getInstantiatedFromMemberTemplate();
1890 } while (Instance);
1891
1892 return false;
1893}
1894
Douglas Gregored9c0f92009-10-29 00:04:11 +00001895static bool
1896isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1897 ClassTemplatePartialSpecializationDecl *Instance) {
1898 Pattern
1899 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1900 do {
1901 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1902 Instance->getCanonicalDecl());
1903 if (Pattern == Instance)
1904 return true;
1905 Instance = Instance->getInstantiatedFromMember();
1906 } while (Instance);
1907
1908 return false;
1909}
1910
John McCall52a575a2009-08-29 08:11:13 +00001911static bool isInstantiationOf(CXXRecordDecl *Pattern,
1912 CXXRecordDecl *Instance) {
1913 Pattern = Pattern->getCanonicalDecl();
1914
1915 do {
1916 Instance = Instance->getCanonicalDecl();
1917 if (Pattern == Instance) return true;
1918 Instance = Instance->getInstantiatedFromMemberClass();
1919 } while (Instance);
1920
1921 return false;
1922}
1923
1924static bool isInstantiationOf(FunctionDecl *Pattern,
1925 FunctionDecl *Instance) {
1926 Pattern = Pattern->getCanonicalDecl();
1927
1928 do {
1929 Instance = Instance->getCanonicalDecl();
1930 if (Pattern == Instance) return true;
1931 Instance = Instance->getInstantiatedFromMemberFunction();
1932 } while (Instance);
1933
1934 return false;
1935}
1936
1937static bool isInstantiationOf(EnumDecl *Pattern,
1938 EnumDecl *Instance) {
1939 Pattern = Pattern->getCanonicalDecl();
1940
1941 do {
1942 Instance = Instance->getCanonicalDecl();
1943 if (Pattern == Instance) return true;
1944 Instance = Instance->getInstantiatedFromMemberEnum();
1945 } while (Instance);
1946
1947 return false;
1948}
1949
John McCalled976492009-12-04 22:46:56 +00001950static bool isInstantiationOf(UsingShadowDecl *Pattern,
1951 UsingShadowDecl *Instance,
1952 ASTContext &C) {
1953 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1954}
1955
1956static bool isInstantiationOf(UsingDecl *Pattern,
1957 UsingDecl *Instance,
1958 ASTContext &C) {
1959 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1960}
1961
John McCall7ba107a2009-11-18 02:36:19 +00001962static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1963 UsingDecl *Instance,
1964 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001965 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001966}
1967
1968static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001969 UsingDecl *Instance,
1970 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001971 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001972}
1973
John McCall52a575a2009-08-29 08:11:13 +00001974static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1975 VarDecl *Instance) {
1976 assert(Instance->isStaticDataMember());
1977
1978 Pattern = Pattern->getCanonicalDecl();
1979
1980 do {
1981 Instance = Instance->getCanonicalDecl();
1982 if (Pattern == Instance) return true;
1983 Instance = Instance->getInstantiatedFromStaticDataMember();
1984 } while (Instance);
1985
1986 return false;
1987}
1988
John McCalled976492009-12-04 22:46:56 +00001989// Other is the prospective instantiation
1990// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001991static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001992 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001993 if (UnresolvedUsingTypenameDecl *UUD
1994 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1995 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1996 return isInstantiationOf(UUD, UD, Ctx);
1997 }
1998 }
1999
2000 if (UnresolvedUsingValueDecl *UUD
2001 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002002 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2003 return isInstantiationOf(UUD, UD, Ctx);
2004 }
2005 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002006
Anders Carlsson0d8df782009-08-29 19:37:28 +00002007 return false;
2008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCall52a575a2009-08-29 08:11:13 +00002010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2011 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall52a575a2009-08-29 08:11:13 +00002013 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2014 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002015
John McCall52a575a2009-08-29 08:11:13 +00002016 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2017 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002018
Douglas Gregor7caa6822009-07-24 20:34:43 +00002019 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002020 if (Var->isStaticDataMember())
2021 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2022
2023 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2024 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002025
Douglas Gregor0d696532009-09-28 06:34:35 +00002026 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2027 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2028
Douglas Gregored9c0f92009-10-29 00:04:11 +00002029 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2030 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2031 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2032 PartialSpec);
2033
Anders Carlssond8b285f2009-09-01 04:26:58 +00002034 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2035 if (!Field->getDeclName()) {
2036 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002037 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002038 cast<FieldDecl>(D);
2039 }
2040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCalled976492009-12-04 22:46:56 +00002042 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2043 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2044
2045 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2046 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2047
Douglas Gregor815215d2009-05-27 05:35:12 +00002048 return D->getDeclName() && isa<NamedDecl>(Other) &&
2049 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2050}
2051
2052template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002053static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002054 NamedDecl *D,
2055 ForwardIterator first,
2056 ForwardIterator last) {
2057 for (; first != last; ++first)
2058 if (isInstantiationOf(Ctx, D, *first))
2059 return cast<NamedDecl>(*first);
2060
2061 return 0;
2062}
2063
John McCall02cace72009-08-28 07:59:38 +00002064/// \brief Finds the instantiation of the given declaration context
2065/// within the current instantiation.
2066///
2067/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002068DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2069 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002070 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002071 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002072 return cast_or_null<DeclContext>(ID);
2073 } else return DC;
2074}
2075
Douglas Gregored961e72009-05-27 17:54:46 +00002076/// \brief Find the instantiation of the given declaration within the
2077/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002078///
2079/// This routine is intended to be used when \p D is a declaration
2080/// referenced from within a template, that needs to mapped into the
2081/// corresponding declaration within an instantiation. For example,
2082/// given:
2083///
2084/// \code
2085/// template<typename T>
2086/// struct X {
2087/// enum Kind {
2088/// KnownValue = sizeof(T)
2089/// };
2090///
2091/// bool getKind() const { return KnownValue; }
2092/// };
2093///
2094/// template struct X<int>;
2095/// \endcode
2096///
2097/// In the instantiation of X<int>::getKind(), we need to map the
2098/// EnumConstantDecl for KnownValue (which refers to
2099/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002100/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2101/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002102NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2103 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002104 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002105 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2106 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2107 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002108 // D is a local of some kind. Look into the map of local
2109 // declarations to their instantiations.
2110 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2111 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002112
Douglas Gregore95b4092009-09-16 18:34:49 +00002113 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2114 if (!Record->isDependentContext())
2115 return D;
2116
2117 // If the RecordDecl is actually the injected-class-name or a "templated"
2118 // declaration for a class template or class template partial
2119 // specialization, substitute into the injected-class-name of the
2120 // class template or partial specialization to find the new DeclContext.
2121 QualType T;
2122 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2123
2124 if (ClassTemplate) {
2125 T = ClassTemplate->getInjectedClassNameType(Context);
2126 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2127 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2128 T = Context.getTypeDeclType(Record);
2129 ClassTemplate = PartialSpec->getSpecializedTemplate();
2130 }
2131
2132 if (!T.isNull()) {
2133 // Substitute into the injected-class-name to get the type corresponding
2134 // to the instantiation we want. This substitution should never fail,
2135 // since we know we can instantiate the injected-class-name or we wouldn't
2136 // have gotten to the injected-class-name!
2137 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2138 // instantiation in the common case?
2139 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2140 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2141
2142 if (!T->isDependentType()) {
2143 assert(T->isRecordType() && "Instantiation must produce a record type");
2144 return T->getAs<RecordType>()->getDecl();
2145 }
2146
2147 // We are performing "partial" template instantiation to create the
2148 // member declarations for the members of a class template
2149 // specialization. Therefore, D is actually referring to something in
2150 // the current instantiation. Look through the current context,
2151 // which contains actual instantiations, to find the instantiation of
2152 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002153 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002154 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002155 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002156 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002157 if (isInstantiationOf(ClassTemplate,
2158 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002159 return Spec;
2160 }
2161
Mike Stump1eb44332009-09-09 15:08:12 +00002162 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002163 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002164 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002165 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002166
2167 // Fall through to deal with other dependent record types (e.g.,
2168 // anonymous unions in class templates).
2169 }
John McCall52a575a2009-08-29 08:11:13 +00002170
Douglas Gregore95b4092009-09-16 18:34:49 +00002171 if (!ParentDC->isDependentContext())
2172 return D;
2173
2174 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002175 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002176 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Douglas Gregor815215d2009-05-27 05:35:12 +00002178 if (ParentDC != D->getDeclContext()) {
2179 // We performed some kind of instantiation in the parent context,
2180 // so now we need to look into the instantiated parent context to
2181 // find the instantiation of the declaration D.
2182 NamedDecl *Result = 0;
2183 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002184 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002185 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2186 } else {
2187 // Since we don't have a name for the entity we're looking for,
2188 // our only option is to walk through all of the declarations to
2189 // find that name. This will occur in a few cases:
2190 //
2191 // - anonymous struct/union within a template
2192 // - unnamed class/struct/union/enum within a template
2193 //
2194 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002195 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002196 ParentDC->decls_begin(),
2197 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002198 }
Mike Stump1eb44332009-09-09 15:08:12 +00002199
John McCall9f54ad42009-12-10 09:41:52 +00002200 // UsingShadowDecls can instantiate to nothing because of using hiding.
2201 assert((Result || isa<UsingShadowDecl>(D))
2202 && "Unable to find instantiation of declaration!");
2203
Douglas Gregor815215d2009-05-27 05:35:12 +00002204 D = Result;
2205 }
2206
Douglas Gregor815215d2009-05-27 05:35:12 +00002207 return D;
2208}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002209
Mike Stump1eb44332009-09-09 15:08:12 +00002210/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002211/// instantiations we have seen until this point.
2212void Sema::PerformPendingImplicitInstantiations() {
2213 while (!PendingImplicitInstantiations.empty()) {
2214 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002215 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Douglas Gregor7caa6822009-07-24 20:34:43 +00002217 // Instantiate function definitions
2218 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002219 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002220 Function->getLocation(), *this,
2221 Context.getSourceManager(),
2222 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002224 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002225 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002226 continue;
2227 }
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregor7caa6822009-07-24 20:34:43 +00002229 // Instantiate static data member definitions.
2230 VarDecl *Var = cast<VarDecl>(Inst.first);
2231 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002232
Mike Stump1eb44332009-09-09 15:08:12 +00002233 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002234 Var->getLocation(), *this,
2235 Context.getSourceManager(),
2236 "instantiating static data member "
2237 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Douglas Gregor7caa6822009-07-24 20:34:43 +00002239 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002240 }
2241}