blob: fe60be062c12096842fe6998b99b3fcc7acfd29c [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"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
Douglas Gregord57a38e2010-04-23 16:25:07 +0000203 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
204 TagDecl *TD = TT->getDecl();
205
206 // If the TagDecl that the TypedefDecl points to is an anonymous decl
207 // keep track of the TypedefDecl.
208 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
209 TD->setTypedefForAnonDecl(Typedef);
210 }
211
John McCall5126fd02009-12-30 00:31:22 +0000212 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000213 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
214 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000215 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
216 }
217
Douglas Gregord57a38e2010-04-23 16:25:07 +0000218
John McCall46460a62010-01-20 21:53:11 +0000219 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000220 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 return Typedef;
223}
224
Douglas Gregor6eef5192009-12-14 19:27:10 +0000225/// \brief Instantiate the arguments provided as part of initialization.
226///
227/// \returns true if an error occurred, false otherwise.
228static bool InstantiateInitializationArguments(Sema &SemaRef,
229 Expr **Args, unsigned NumArgs,
230 const MultiLevelTemplateArgumentList &TemplateArgs,
231 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
232 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
233 for (unsigned I = 0; I != NumArgs; ++I) {
234 // When we hit the first defaulted argument, break out of the loop:
235 // we don't pass those default arguments on.
236 if (Args[I]->isDefaultArgument())
237 break;
238
239 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
240 if (Arg.isInvalid())
241 return true;
242
243 Expr *ArgExpr = (Expr *)Arg.get();
244 InitArgs.push_back(Arg.release());
245
246 // FIXME: We're faking all of the comma locations. Do we need them?
247 FakeCommaLocs.push_back(
248 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
249 }
250
251 return false;
252}
253
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000254/// \brief Instantiate an initializer, breaking it into separate
255/// initialization arguments.
256///
257/// \param S The semantic analysis object.
258///
259/// \param Init The initializer to instantiate.
260///
261/// \param TemplateArgs Template arguments to be substituted into the
262/// initializer.
263///
264/// \param NewArgs Will be filled in with the instantiation arguments.
265///
266/// \returns true if an error occurred, false otherwise
267static bool InstantiateInitializer(Sema &S, Expr *Init,
268 const MultiLevelTemplateArgumentList &TemplateArgs,
269 SourceLocation &LParenLoc,
270 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
271 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
272 SourceLocation &RParenLoc) {
273 NewArgs.clear();
274 LParenLoc = SourceLocation();
275 RParenLoc = SourceLocation();
276
277 if (!Init)
278 return false;
279
280 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
281 Init = ExprTemp->getSubExpr();
282
283 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
284 Init = Binder->getSubExpr();
285
286 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
287 Init = ICE->getSubExprAsWritten();
288
289 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
290 LParenLoc = ParenList->getLParenLoc();
291 RParenLoc = ParenList->getRParenLoc();
292 return InstantiateInitializationArguments(S, ParenList->getExprs(),
293 ParenList->getNumExprs(),
294 TemplateArgs, CommaLocs,
295 NewArgs);
296 }
297
298 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000299 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
300 if (InstantiateInitializationArguments(S,
301 Construct->getArgs(),
302 Construct->getNumArgs(),
303 TemplateArgs,
304 CommaLocs, NewArgs))
305 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000306
Douglas Gregor28329e52010-03-24 21:22:47 +0000307 // FIXME: Fake locations!
308 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
309 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
310 return false;
311 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000312 }
313
314 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
315 if (Result.isInvalid())
316 return true;
317
318 NewArgs.push_back(Result.takeAs<Expr>());
319 return false;
320}
321
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000323 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000324 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000325 TemplateArgs,
326 D->getTypeSpecStartLoc(),
327 D->getDeclName());
328 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000329 return 0;
330
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000331 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000332 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
333 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000334 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000335 D->getStorageClass(),
336 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000337 Var->setThreadSpecified(D->isThreadSpecified());
338 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
339 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCallb6217662010-03-15 10:12:16 +0000341 // Substitute the nested name specifier, if any.
342 if (SubstQualifier(D, Var))
343 return 0;
344
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000346 // out-of-line, the instantiation will have the same lexical
347 // context (which will be a namespace scope) as the template.
348 if (D->isOutOfLine())
349 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000350
John McCall46460a62010-01-20 21:53:11 +0000351 Var->setAccess(D->getAccess());
352
Mike Stump390b4cc2009-05-16 07:39:55 +0000353 // FIXME: In theory, we could have a previous declaration for variables that
354 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000355 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000356 // FIXME: having to fake up a LookupResult is dumb.
357 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000358 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000359 if (D->isStaticDataMember())
360 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000361 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Douglas Gregor7caa6822009-07-24 20:34:43 +0000363 if (D->isOutOfLine()) {
364 D->getLexicalDeclContext()->addDecl(Var);
365 Owner->makeDeclVisibleInContext(Var);
366 } else {
367 Owner->addDecl(Var);
368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000370 // Link instantiations of static data members back to the template from
371 // which they were instantiated.
372 if (Var->isStaticDataMember())
373 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000374 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000375
Douglas Gregor60c93c92010-02-09 07:26:29 +0000376 if (Var->getAnyInitializer()) {
377 // We already have an initializer in the class.
378 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000379 if (Var->isStaticDataMember() && !D->isOutOfLine())
380 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
381 else
382 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
383
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000384 // Instantiate the initializer.
385 SourceLocation LParenLoc, RParenLoc;
386 llvm::SmallVector<SourceLocation, 4> CommaLocs;
387 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
388 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
389 CommaLocs, InitArgs, RParenLoc)) {
390 // Attach the initializer to the declaration.
391 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000392 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000393 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000394 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 move_arg(InitArgs),
396 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 RParenLoc);
398 } else if (InitArgs.size() == 1) {
399 Expr *Init = (Expr*)(InitArgs.take()[0]);
400 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
401 SemaRef.Owned(Init),
402 false);
403 } else {
404 assert(InitArgs.size() == 0);
405 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000406 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000407 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000408 // FIXME: Not too happy about invalidating the declaration
409 // because of a bogus initializer.
410 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000411 }
412
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000414 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
415 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000416
417 return Var;
418}
419
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
421 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000422 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000423 if (DI->getType()->isDependentType()) {
424 DI = SemaRef.SubstType(DI, TemplateArgs,
425 D->getLocation(), D->getDeclName());
426 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000427 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000428 Invalid = true;
429 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 // C++ [temp.arg.type]p3:
431 // If a declaration acquires a function type through a type
432 // dependent on a template-parameter and this causes a
433 // declaration that does not use the syntactic form of a
434 // function declarator to have function type, the program is
435 // ill-formed.
436 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000437 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 Invalid = true;
439 }
440 }
441
442 Expr *BitWidth = D->getBitWidth();
443 if (Invalid)
444 BitWidth = 0;
445 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000446 // The bit-width expression is not potentially evaluated.
447 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000449 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000450 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000451 if (InstantiatedBitWidth.isInvalid()) {
452 Invalid = true;
453 BitWidth = 0;
454 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000455 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
457
John McCall07fb6be2009-10-22 23:33:21 +0000458 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
459 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000460 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000461 D->getLocation(),
462 D->isMutable(),
463 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000464 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000465 D->getAccess(),
466 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000467 if (!Field) {
468 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000469 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000472 InstantiateAttrs(D, Field);
473
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000474 if (Invalid)
475 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000477 if (!Field->getDeclName()) {
478 // Keep track of where this decl came from.
479 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000482 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000483 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000484 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485
486 return Field;
487}
488
John McCall02cace72009-08-28 07:59:38 +0000489Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000490 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000491 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000492 if (TypeSourceInfo *Ty = D->getFriendType()) {
493 TypeSourceInfo *InstTy =
494 SemaRef.SubstType(Ty, TemplateArgs,
495 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000496 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000497 return 0;
John McCall02cace72009-08-28 07:59:38 +0000498
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
500 if (!FD)
501 return 0;
502
503 FD->setAccess(AS_public);
504 Owner->addDecl(FD);
505 return FD;
506 }
507
508 NamedDecl *ND = D->getFriendDecl();
509 assert(ND && "friend decl must be a decl or a type!");
510
John McCallaf2094e2010-04-08 09:05:18 +0000511 // All of the Visit implementations for the various potential friend
512 // declarations have to be carefully written to work for friend
513 // objects, with the most important detail being that the target
514 // decl should almost certainly not be placed in Owner.
515 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000516 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
John McCall02cace72009-08-28 07:59:38 +0000518 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000519 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
520 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000521 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000522 Owner->addDecl(FD);
523 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000524}
525
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000526Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
527 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregorac7610d2009-06-22 20:57:11 +0000529 // The expression in a static assertion is not potentially evaluated.
530 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000532 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000533 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534 if (InstantiatedAssertExpr.isInvalid())
535 return 0;
536
Douglas Gregor43d9d922009-08-08 01:41:12 +0000537 OwningExprResult Message(SemaRef, D->getMessage());
538 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 Decl *StaticAssert
540 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000541 move(InstantiatedAssertExpr),
542 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000543 return StaticAssert;
544}
545
546Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000547 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000548 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000549 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000551 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000552 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000553 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000554 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000555 Enum->startDefinition();
556
Douglas Gregor96084f12010-03-01 19:00:07 +0000557 if (D->getDeclContext()->isFunctionOrMethod())
558 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
559
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000560 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000561
562 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000563 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
564 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000565 EC != ECEnd; ++EC) {
566 // The specified value for the enumerator.
567 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000568 if (Expr *UninstValue = EC->getInitExpr()) {
569 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000570 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000571 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
John McCallce3ff2b2009-08-25 22:02:44 +0000573 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000574 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000575
576 // Drop the initial value and continue.
577 bool isInvalid = false;
578 if (Value.isInvalid()) {
579 Value = SemaRef.Owned((Expr *)0);
580 isInvalid = true;
581 }
582
Mike Stump1eb44332009-09-09 15:08:12 +0000583 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000584 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
585 EC->getLocation(), EC->getIdentifier(),
586 move(Value));
587
588 if (isInvalid) {
589 if (EnumConst)
590 EnumConst->setInvalidDecl();
591 Enum->setInvalidDecl();
592 }
593
594 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000595 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000596 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000597 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000598 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000599
600 if (D->getDeclContext()->isFunctionOrMethod()) {
601 // If the enumeration is within a function or method, record the enum
602 // constant as a local.
603 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
604 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605 }
606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000608 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000609 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000610 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
611 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000612 &Enumerators[0], Enumerators.size(),
613 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000614
615 return Enum;
616}
617
Douglas Gregor6477b692009-03-25 15:04:13 +0000618Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
619 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
620 return 0;
621}
622
Douglas Gregored9c0f92009-10-29 00:04:11 +0000623namespace {
624 class SortDeclByLocation {
625 SourceManager &SourceMgr;
626
627 public:
628 explicit SortDeclByLocation(SourceManager &SourceMgr)
629 : SourceMgr(SourceMgr) { }
630
631 bool operator()(const Decl *X, const Decl *Y) const {
632 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
633 Y->getLocation());
634 }
635 };
636}
637
John McCalle29ba202009-08-20 01:44:21 +0000638Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000639 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
640
Douglas Gregor550d9b22009-10-31 17:21:17 +0000641 // Create a local instantiation scope for this class template, which
642 // will contain the instantiations of the template parameters.
643 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000644 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000645 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000646 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000647 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000648
649 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000650
651 // Instantiate the qualifier. We have to do this first in case
652 // we're a friend declaration, because if we are then we need to put
653 // the new declaration in the appropriate context.
654 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
655 if (Qualifier) {
656 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
657 Pattern->getQualifierRange(),
658 TemplateArgs);
659 if (!Qualifier) return 0;
660 }
661
662 CXXRecordDecl *PrevDecl = 0;
663 ClassTemplateDecl *PrevClassTemplate = 0;
664
665 // If this isn't a friend, then it's a member template, in which
666 // case we just want to build the instantiation in the
667 // specialization. If it is a friend, we want to build it in
668 // the appropriate context.
669 DeclContext *DC = Owner;
670 if (isFriend) {
671 if (Qualifier) {
672 CXXScopeSpec SS;
673 SS.setScopeRep(Qualifier);
674 SS.setRange(Pattern->getQualifierRange());
675 DC = SemaRef.computeDeclContext(SS);
676 if (!DC) return 0;
677 } else {
678 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
679 Pattern->getDeclContext(),
680 TemplateArgs);
681 }
682
683 // Look for a previous declaration of the template in the owning
684 // context.
685 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
686 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
687 SemaRef.LookupQualifiedName(R, DC);
688
689 if (R.isSingleResult()) {
690 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
691 if (PrevClassTemplate)
692 PrevDecl = PrevClassTemplate->getTemplatedDecl();
693 }
694
695 if (!PrevClassTemplate && Qualifier) {
696 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000697 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
698 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000699 return 0;
700 }
701
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000702 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000703 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000704 bool Complain = true;
705
706 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
707 // template for struct std::tr1::__detail::_Map_base, where the
708 // template parameters of the friend declaration don't match the
709 // template parameters of the original declaration. In this one
710 // case, we don't complain about the ill-formed friend
711 // declaration.
712 if (isFriend && Pattern->getIdentifier() &&
713 Pattern->getIdentifier()->isStr("_Map_base") &&
714 DC->isNamespace() &&
715 cast<NamespaceDecl>(DC)->getIdentifier() &&
716 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
717 DeclContext *DCParent = DC->getParent();
718 if (DCParent->isNamespace() &&
719 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
720 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
721 DeclContext *DCParent2 = DCParent->getParent();
722 if (DCParent2->isNamespace() &&
723 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
724 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
725 DCParent2->getParent()->isTranslationUnit())
726 Complain = false;
727 }
728 }
729
John McCall93ba8572010-03-25 06:39:04 +0000730 TemplateParameterList *PrevParams
731 = PrevClassTemplate->getTemplateParameters();
732
733 // Make sure the parameter lists match.
734 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000735 Complain,
736 Sema::TPL_TemplateMatch)) {
737 if (Complain)
738 return 0;
739
740 AdoptedPreviousTemplateParams = true;
741 InstParams = PrevParams;
742 }
John McCall93ba8572010-03-25 06:39:04 +0000743
744 // Do some additional validation, then merge default arguments
745 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000746 if (!AdoptedPreviousTemplateParams &&
747 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000748 Sema::TPC_ClassTemplate))
749 return 0;
750 }
751 }
752
John McCalle29ba202009-08-20 01:44:21 +0000753 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000754 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000755 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000756 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000757 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000758
John McCall93ba8572010-03-25 06:39:04 +0000759 if (Qualifier)
760 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000761
John McCalle29ba202009-08-20 01:44:21 +0000762 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000763 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
764 D->getIdentifier(), InstParams, RecordInst,
765 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000766 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000767
John McCall93ba8572010-03-25 06:39:04 +0000768 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000769 if (PrevClassTemplate)
770 Inst->setAccess(PrevClassTemplate->getAccess());
771 else
772 Inst->setAccess(D->getAccess());
773
John McCall93ba8572010-03-25 06:39:04 +0000774 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
775 // TODO: do we want to track the instantiation progeny of this
776 // friend target decl?
777 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000779 Inst->setInstantiatedFromMemberTemplate(D);
780 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000781
782 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000783 SemaRef.Context.getInjectedClassNameType(RecordInst,
784 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000785
Douglas Gregor259571e2009-10-30 22:42:42 +0000786 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000787 if (isFriend) {
788 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000789 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000790 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000791
John McCalle29ba202009-08-20 01:44:21 +0000792 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000793
794 // First, we sort the partial specializations by location, so
795 // that we instantiate them in the order they were declared.
796 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
797 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
798 P = D->getPartialSpecializations().begin(),
799 PEnd = D->getPartialSpecializations().end();
800 P != PEnd; ++P)
801 PartialSpecs.push_back(&*P);
802 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
803 SortDeclByLocation(SemaRef.SourceMgr));
804
805 // Instantiate all of the partial specializations of this member class
806 // template.
807 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
808 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
809
John McCalle29ba202009-08-20 01:44:21 +0000810 return Inst;
811}
812
Douglas Gregord60e1052009-08-27 16:57:43 +0000813Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000814TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
815 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000816 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
817
818 // Lookup the already-instantiated declaration in the instantiation
819 // of the class template and return that.
820 DeclContext::lookup_result Found
821 = Owner->lookup(ClassTemplate->getDeclName());
822 if (Found.first == Found.second)
823 return 0;
824
825 ClassTemplateDecl *InstClassTemplate
826 = dyn_cast<ClassTemplateDecl>(*Found.first);
827 if (!InstClassTemplate)
828 return 0;
829
830 Decl *DCanon = D->getCanonicalDecl();
831 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
832 P = InstClassTemplate->getPartialSpecializations().begin(),
833 PEnd = InstClassTemplate->getPartialSpecializations().end();
834 P != PEnd; ++P) {
835 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
836 return &*P;
837 }
838
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000839 return 0;
840}
841
842Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000843TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000844 // Create a local instantiation scope for this function template, which
845 // will contain the instantiations of the template parameters and then get
846 // merged with the local instantiation scope for the function template
847 // itself.
848 Sema::LocalInstantiationScope Scope(SemaRef);
849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 TemplateParameterList *TempParams = D->getTemplateParameters();
851 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000852 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000853 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000854
Douglas Gregora735b202009-10-13 14:39:41 +0000855 FunctionDecl *Instantiated = 0;
856 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
857 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
858 InstParams));
859 else
860 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
861 D->getTemplatedDecl(),
862 InstParams));
863
864 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000865 return 0;
866
John McCall46460a62010-01-20 21:53:11 +0000867 Instantiated->setAccess(D->getAccess());
868
Mike Stump1eb44332009-09-09 15:08:12 +0000869 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000871 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000872 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000873 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000874 assert(InstTemplate &&
875 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000876
John McCallb1a56e72010-03-26 23:10:15 +0000877 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
878
John McCalle976ffe2009-12-14 23:19:40 +0000879 // Link the instantiation back to the pattern *unless* this is a
880 // non-definition friend declaration.
881 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000882 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000883 InstTemplate->setInstantiatedFromMemberTemplate(D);
884
John McCallb1a56e72010-03-26 23:10:15 +0000885 // Make declarations visible in the appropriate context.
886 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000887 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000888
Douglas Gregord60e1052009-08-27 16:57:43 +0000889 return InstTemplate;
890}
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
893 CXXRecordDecl *PrevDecl = 0;
894 if (D->isInjectedClassName())
895 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000896 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000897 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
898 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000899 TemplateArgs);
900 if (!Prev) return 0;
901 PrevDecl = cast<CXXRecordDecl>(Prev);
902 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000903
904 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000905 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000906 D->getLocation(), D->getIdentifier(),
907 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000908
909 // Substitute the nested name specifier, if any.
910 if (SubstQualifier(D, Record))
911 return 0;
912
Douglas Gregord475b8d2009-03-25 21:17:03 +0000913 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000914 // FIXME: Check against AS_none is an ugly hack to work around the issue that
915 // the tag decls introduced by friend class declarations don't have an access
916 // specifier. Remove once this area of the code gets sorted out.
917 if (D->getAccess() != AS_none)
918 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000919 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000920 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000921
John McCall02cace72009-08-28 07:59:38 +0000922 // If the original function was part of a friend declaration,
923 // inherit its namespace state.
924 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
925 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
926
Anders Carlssond8b285f2009-09-01 04:26:58 +0000927 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
928
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000929 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000930 return Record;
931}
932
John McCall02cace72009-08-28 07:59:38 +0000933/// Normal class members are of more specific types and therefore
934/// don't make it here. This function serves two purposes:
935/// 1) instantiating function templates
936/// 2) substituting friend declarations
937/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000938Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000939 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000940 // Check whether there is already a function template specialization for
941 // this declaration.
942 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
943 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000944 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000945 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000946 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000947 TemplateArgs.getInnermost().getFlatArgumentList(),
948 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000949 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
951 FunctionTemplateSpecializationInfo *Info
952 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000953 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregor127102b2009-06-29 20:59:39 +0000955 // If we already have a function template specialization, return it.
956 if (Info)
957 return Info->Function;
958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
John McCallb0cb0222010-03-27 05:57:59 +0000960 bool isFriend;
961 if (FunctionTemplate)
962 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
963 else
964 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
965
Douglas Gregor79c22782010-01-16 20:21:20 +0000966 bool MergeWithParentScope = (TemplateParams != 0) ||
967 !(isa<Decl>(Owner) &&
968 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
969 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregore53060f2009-06-25 22:08:12 +0000971 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000972 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
973 TInfo = SubstFunctionType(D, Params);
974 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000975 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000976 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000977
John McCalld325daa2010-03-26 04:53:08 +0000978 NestedNameSpecifier *Qualifier = D->getQualifier();
979 if (Qualifier) {
980 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
981 D->getQualifierRange(),
982 TemplateArgs);
983 if (!Qualifier) return 0;
984 }
985
John McCall68b6b872010-02-06 01:50:47 +0000986 // If we're instantiating a local function declaration, put the result
987 // in the owner; otherwise we need to find the instantiated context.
988 DeclContext *DC;
989 if (D->getDeclContext()->isFunctionOrMethod())
990 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000991 else if (isFriend && Qualifier) {
992 CXXScopeSpec SS;
993 SS.setScopeRep(Qualifier);
994 SS.setRange(D->getQualifierRange());
995 DC = SemaRef.computeDeclContext(SS);
996 if (!DC) return 0;
997 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000998 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
999 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001000 }
John McCall68b6b872010-02-06 01:50:47 +00001001
John McCall02cace72009-08-28 07:59:38 +00001002 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001003 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001004 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001005 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001006 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001007
John McCalld325daa2010-03-26 04:53:08 +00001008 if (Qualifier)
1009 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001010
John McCallb1a56e72010-03-26 23:10:15 +00001011 DeclContext *LexicalDC = Owner;
1012 if (!isFriend && D->isOutOfLine()) {
1013 assert(D->getDeclContext()->isFileContext());
1014 LexicalDC = D->getDeclContext();
1015 }
1016
1017 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Douglas Gregore53060f2009-06-25 22:08:12 +00001019 // Attach the parameters
1020 for (unsigned P = 0; P < Params.size(); ++P)
1021 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001022 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001023
Douglas Gregora735b202009-10-13 14:39:41 +00001024 if (TemplateParams) {
1025 // Our resulting instantiation is actually a function template, since we
1026 // are substituting only the outer template parameters. For example, given
1027 //
1028 // template<typename T>
1029 // struct X {
1030 // template<typename U> friend void f(T, U);
1031 // };
1032 //
1033 // X<int> x;
1034 //
1035 // We are instantiating the friend function template "f" within X<int>,
1036 // which means substituting int for T, but leaving "f" as a friend function
1037 // template.
1038 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001039 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001040 Function->getLocation(),
1041 Function->getDeclName(),
1042 TemplateParams, Function);
1043 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001044
1045 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001046
1047 if (isFriend && D->isThisDeclarationADefinition()) {
1048 // TODO: should we remember this connection regardless of whether
1049 // the friend declaration provided a body?
1050 FunctionTemplate->setInstantiatedFromMemberTemplate(
1051 D->getDescribedFunctionTemplate());
1052 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001053 } else if (FunctionTemplate) {
1054 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001055 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001056 &TemplateArgs.getInnermost(),
1057 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001058 } else if (isFriend && D->isThisDeclarationADefinition()) {
1059 // TODO: should we remember this connection regardless of whether
1060 // the friend declaration provided a body?
1061 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001062 }
Douglas Gregora735b202009-10-13 14:39:41 +00001063
Douglas Gregore53060f2009-06-25 22:08:12 +00001064 if (InitFunctionInstantiation(Function, D))
1065 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregore53060f2009-06-25 22:08:12 +00001067 bool Redeclaration = false;
1068 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001069 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001070
John McCall68263142009-11-18 22:49:29 +00001071 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1072 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1073
John McCallaf2094e2010-04-08 09:05:18 +00001074 if (DependentFunctionTemplateSpecializationInfo *Info
1075 = D->getDependentSpecializationInfo()) {
1076 assert(isFriend && "non-friend has dependent specialization info?");
1077
1078 // This needs to be set now for future sanity.
1079 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1080
1081 // Instantiate the explicit template arguments.
1082 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1083 Info->getRAngleLoc());
1084 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1085 TemplateArgumentLoc Loc;
1086 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1087 return 0;
1088
1089 ExplicitArgs.addArgument(Loc);
1090 }
1091
1092 // Map the candidate templates to their instantiations.
1093 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1094 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1095 Info->getTemplate(I),
1096 TemplateArgs);
1097 if (!Temp) return 0;
1098
1099 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1100 }
1101
1102 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1103 &ExplicitArgs,
1104 Previous))
1105 Function->setInvalidDecl();
1106
1107 isExplicitSpecialization = true;
1108
1109 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // Look only into the namespace where the friend would be declared to
1111 // find a previous declaration. This is the innermost enclosing namespace,
1112 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001113 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001114
Douglas Gregora735b202009-10-13 14:39:41 +00001115 // In C++, the previous declaration we find might be a tag type
1116 // (class or enum). In this case, the new declaration will hide the
1117 // tag type. Note that this does does not apply if we're declaring a
1118 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001119 if (Previous.isSingleTagDecl())
1120 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001121 }
1122
John McCall9f54ad42009-12-10 09:41:52 +00001123 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001124 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001125 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001126
Douglas Gregora735b202009-10-13 14:39:41 +00001127 // If the original function was part of a friend declaration,
1128 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001129 if (isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001130 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +00001131 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +00001132 if (TemplateParams) {
1133 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1134 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1135 } else {
1136 ToFriendD = Function;
1137 PrevDecl = Function->getPreviousDeclaration();
1138 }
1139 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalld325daa2010-03-26 04:53:08 +00001140 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001141 }
1142
Douglas Gregore53060f2009-06-25 22:08:12 +00001143 return Function;
1144}
1145
Douglas Gregord60e1052009-08-27 16:57:43 +00001146Decl *
1147TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1148 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001149 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1150 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001151 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001152 // We are creating a function template specialization from a function
1153 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001154 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001155 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001156 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001157 TemplateArgs.getInnermost().getFlatArgumentList(),
1158 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001159 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
1161 FunctionTemplateSpecializationInfo *Info
1162 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001163 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Douglas Gregor6b906862009-08-21 00:16:32 +00001165 // If we already have a function template specialization, return it.
1166 if (Info)
1167 return Info->Function;
1168 }
1169
John McCallb0cb0222010-03-27 05:57:59 +00001170 bool isFriend;
1171 if (FunctionTemplate)
1172 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1173 else
1174 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1175
Douglas Gregor79c22782010-01-16 20:21:20 +00001176 bool MergeWithParentScope = (TemplateParams != 0) ||
1177 !(isa<Decl>(Owner) &&
1178 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1179 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001180
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001181 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001182 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1183 TInfo = SubstFunctionType(D, Params);
1184 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001185 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001186 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001187
John McCallb0cb0222010-03-27 05:57:59 +00001188 NestedNameSpecifier *Qualifier = D->getQualifier();
1189 if (Qualifier) {
1190 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1191 D->getQualifierRange(),
1192 TemplateArgs);
1193 if (!Qualifier) return 0;
1194 }
1195
1196 DeclContext *DC = Owner;
1197 if (isFriend) {
1198 if (Qualifier) {
1199 CXXScopeSpec SS;
1200 SS.setScopeRep(Qualifier);
1201 SS.setRange(D->getQualifierRange());
1202 DC = SemaRef.computeDeclContext(SS);
1203 } else {
1204 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1205 D->getDeclContext(),
1206 TemplateArgs);
1207 }
1208 if (!DC) return 0;
1209 }
1210
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001211 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001212 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001213 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Douglas Gregordec06662009-08-21 18:42:58 +00001215 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001216 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001217 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1218 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1219 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001220 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1221 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001222 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001223 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001224 Constructor->isInlineSpecified(),
1225 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001226 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1227 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1228 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1229 SemaRef.Context.getCanonicalType(ClassTy));
1230 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1231 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001232 T, Destructor->isInlineSpecified(),
1233 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001234 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001235 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001236 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001237 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001238 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1239 ConvTy);
1240 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1241 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001242 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001243 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001244 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001245 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001246 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001247 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001248 D->isStatic(),
1249 D->getStorageClassAsWritten(),
1250 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001251 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001252
John McCallb0cb0222010-03-27 05:57:59 +00001253 if (Qualifier)
1254 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001255
Douglas Gregord60e1052009-08-27 16:57:43 +00001256 if (TemplateParams) {
1257 // Our resulting instantiation is actually a function template, since we
1258 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001259 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001260 // template<typename T>
1261 // struct X {
1262 // template<typename U> void f(T, U);
1263 // };
1264 //
1265 // X<int> x;
1266 //
1267 // We are instantiating the member template "f" within X<int>, which means
1268 // substituting int for T, but leaving "f" as a member function template.
1269 // Build the function template itself.
1270 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1271 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001272 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001273 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001274 if (isFriend) {
1275 FunctionTemplate->setLexicalDeclContext(Owner);
1276 FunctionTemplate->setObjectOfFriendDecl(true);
1277 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001278 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001279 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001280 } else if (FunctionTemplate) {
1281 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001282 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001283 &TemplateArgs.getInnermost(),
1284 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001285 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001286 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001287 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001288 }
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001291 // out-of-line, the instantiation will have the same lexical
1292 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001293 if (isFriend) {
1294 Method->setLexicalDeclContext(Owner);
1295 Method->setObjectOfFriendDecl(true);
1296 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001297 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregor5545e162009-03-24 00:38:23 +00001299 // Attach the parameters
1300 for (unsigned P = 0; P < Params.size(); ++P)
1301 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001302 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001303
1304 if (InitMethodInstantiation(Method, D))
1305 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001306
John McCall68263142009-11-18 22:49:29 +00001307 LookupResult Previous(SemaRef, Name, SourceLocation(),
1308 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
John McCallb0cb0222010-03-27 05:57:59 +00001310 if (!FunctionTemplate || TemplateParams || isFriend) {
1311 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Douglas Gregordec06662009-08-21 18:42:58 +00001313 // In C++, the previous declaration we find might be a tag type
1314 // (class or enum). In this case, the new declaration will hide the
1315 // tag type. Note that this does does not apply if we're declaring a
1316 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001317 if (Previous.isSingleTagDecl())
1318 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001319 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001320
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001321 bool Redeclaration = false;
1322 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001323 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001324 /*FIXME:*/OverloadableAttrRequired);
1325
Douglas Gregor4ba31362009-12-01 17:24:26 +00001326 if (D->isPure())
1327 SemaRef.CheckPureMethod(Method, SourceRange());
1328
John McCall46460a62010-01-20 21:53:11 +00001329 Method->setAccess(D->getAccess());
1330
John McCallb0cb0222010-03-27 05:57:59 +00001331 if (FunctionTemplate) {
1332 // If there's a function template, let our caller handle it.
1333 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1334 // Don't hide a (potentially) valid declaration with an invalid one.
1335 } else {
1336 NamedDecl *DeclToAdd = (TemplateParams
1337 ? cast<NamedDecl>(FunctionTemplate)
1338 : Method);
1339 if (isFriend)
1340 Record->makeDeclVisibleInContext(DeclToAdd);
1341 else
1342 Owner->addDecl(DeclToAdd);
1343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001345 return Method;
1346}
1347
Douglas Gregor615c5d42009-03-24 16:43:20 +00001348Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001349 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001350}
1351
Douglas Gregor03b2b072009-03-24 00:15:49 +00001352Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001353 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001354}
1355
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001356Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001357 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001358}
1359
Douglas Gregor6477b692009-03-25 15:04:13 +00001360ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001361 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001362}
1363
John McCalle29ba202009-08-20 01:44:21 +00001364Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1365 TemplateTypeParmDecl *D) {
1366 // TODO: don't always clone when decls are refcounted.
1367 const Type* T = D->getTypeForDecl();
1368 assert(T->isTemplateTypeParmType());
1369 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001370
John McCalle29ba202009-08-20 01:44:21 +00001371 TemplateTypeParmDecl *Inst =
1372 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001373 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001374 TTPT->getName(),
1375 D->wasDeclaredWithTypename(),
1376 D->isParameterPack());
1377
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001378 if (D->hasDefaultArgument())
1379 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001380
Douglas Gregor550d9b22009-10-31 17:21:17 +00001381 // Introduce this template parameter's instantiation into the instantiation
1382 // scope.
1383 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1384
John McCalle29ba202009-08-20 01:44:21 +00001385 return Inst;
1386}
1387
Douglas Gregor33642df2009-10-23 23:25:44 +00001388Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1389 NonTypeTemplateParmDecl *D) {
1390 // Substitute into the type of the non-type template parameter.
1391 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001392 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001393 if (DI) {
1394 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1395 D->getDeclName());
1396 if (DI) T = DI->getType();
1397 } else {
1398 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1399 D->getDeclName());
1400 DI = 0;
1401 }
1402 if (T.isNull())
1403 return 0;
1404
1405 // Check that this type is acceptable for a non-type template parameter.
1406 bool Invalid = false;
1407 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1408 if (T.isNull()) {
1409 T = SemaRef.Context.IntTy;
1410 Invalid = true;
1411 }
1412
1413 NonTypeTemplateParmDecl *Param
1414 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1415 D->getDepth() - 1, D->getPosition(),
1416 D->getIdentifier(), T, DI);
1417 if (Invalid)
1418 Param->setInvalidDecl();
1419
1420 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001421
1422 // Introduce this template parameter's instantiation into the instantiation
1423 // scope.
1424 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001425 return Param;
1426}
1427
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001428Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001429TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1430 TemplateTemplateParmDecl *D) {
1431 // Instantiate the template parameter list of the template template parameter.
1432 TemplateParameterList *TempParams = D->getTemplateParameters();
1433 TemplateParameterList *InstParams;
1434 {
1435 // Perform the actual substitution of template parameters within a new,
1436 // local instantiation scope.
1437 Sema::LocalInstantiationScope Scope(SemaRef);
1438 InstParams = SubstTemplateParams(TempParams);
1439 if (!InstParams)
1440 return NULL;
1441 }
1442
1443 // Build the template template parameter.
1444 TemplateTemplateParmDecl *Param
1445 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1446 D->getDepth() - 1, D->getPosition(),
1447 D->getIdentifier(), InstParams);
1448 Param->setDefaultArgument(D->getDefaultArgument());
1449
1450 // Introduce this template parameter's instantiation into the instantiation
1451 // scope.
1452 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1453
1454 return Param;
1455}
1456
Douglas Gregor48c32a72009-11-17 06:07:40 +00001457Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1458 // Using directives are never dependent, so they require no explicit
1459
1460 UsingDirectiveDecl *Inst
1461 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1462 D->getNamespaceKeyLocation(),
1463 D->getQualifierRange(), D->getQualifier(),
1464 D->getIdentLocation(),
1465 D->getNominatedNamespace(),
1466 D->getCommonAncestor());
1467 Owner->addDecl(Inst);
1468 return Inst;
1469}
1470
John McCalled976492009-12-04 22:46:56 +00001471Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1472 // The nested name specifier is non-dependent, so no transformation
1473 // is required.
1474
John McCall9f54ad42009-12-10 09:41:52 +00001475 // We only need to do redeclaration lookups if we're in a class
1476 // scope (in fact, it's not really even possible in non-class
1477 // scopes).
1478 bool CheckRedeclaration = Owner->isRecord();
1479
1480 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1481 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1482
John McCalled976492009-12-04 22:46:56 +00001483 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1484 D->getLocation(),
1485 D->getNestedNameRange(),
1486 D->getUsingLocation(),
1487 D->getTargetNestedNameDecl(),
1488 D->getDeclName(),
1489 D->isTypeName());
1490
1491 CXXScopeSpec SS;
1492 SS.setScopeRep(D->getTargetNestedNameDecl());
1493 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001494
1495 if (CheckRedeclaration) {
1496 Prev.setHideTags(false);
1497 SemaRef.LookupQualifiedName(Prev, Owner);
1498
1499 // Check for invalid redeclarations.
1500 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1501 D->isTypeName(), SS,
1502 D->getLocation(), Prev))
1503 NewUD->setInvalidDecl();
1504
1505 }
1506
1507 if (!NewUD->isInvalidDecl() &&
1508 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001509 D->getLocation()))
1510 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001511
John McCalled976492009-12-04 22:46:56 +00001512 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1513 NewUD->setAccess(D->getAccess());
1514 Owner->addDecl(NewUD);
1515
John McCall9f54ad42009-12-10 09:41:52 +00001516 // Don't process the shadow decls for an invalid decl.
1517 if (NewUD->isInvalidDecl())
1518 return NewUD;
1519
John McCall323c3102009-12-22 22:26:37 +00001520 bool isFunctionScope = Owner->isFunctionOrMethod();
1521
John McCall9f54ad42009-12-10 09:41:52 +00001522 // Process the shadow decls.
1523 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1524 I != E; ++I) {
1525 UsingShadowDecl *Shadow = *I;
1526 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001527 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1528 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001529 TemplateArgs));
1530
1531 if (CheckRedeclaration &&
1532 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1533 continue;
1534
1535 UsingShadowDecl *InstShadow
1536 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1537 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001538
1539 if (isFunctionScope)
1540 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001541 }
John McCalled976492009-12-04 22:46:56 +00001542
1543 return NewUD;
1544}
1545
1546Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001547 // Ignore these; we handle them in bulk when processing the UsingDecl.
1548 return 0;
John McCalled976492009-12-04 22:46:56 +00001549}
1550
John McCall7ba107a2009-11-18 02:36:19 +00001551Decl * TemplateDeclInstantiator
1552 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001553 NestedNameSpecifier *NNS =
1554 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1555 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001556 TemplateArgs);
1557 if (!NNS)
1558 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001560 CXXScopeSpec SS;
1561 SS.setRange(D->getTargetNestedNameRange());
1562 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
1564 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001565 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001566 D->getUsingLoc(), SS, D->getLocation(),
1567 D->getDeclName(), 0,
1568 /*instantiation*/ true,
1569 /*typename*/ true, D->getTypenameLoc());
1570 if (UD)
John McCalled976492009-12-04 22:46:56 +00001571 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1572
John McCall7ba107a2009-11-18 02:36:19 +00001573 return UD;
1574}
1575
1576Decl * TemplateDeclInstantiator
1577 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1578 NestedNameSpecifier *NNS =
1579 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1580 D->getTargetNestedNameRange(),
1581 TemplateArgs);
1582 if (!NNS)
1583 return 0;
1584
1585 CXXScopeSpec SS;
1586 SS.setRange(D->getTargetNestedNameRange());
1587 SS.setScopeRep(NNS);
1588
1589 NamedDecl *UD =
1590 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1591 D->getUsingLoc(), SS, D->getLocation(),
1592 D->getDeclName(), 0,
1593 /*instantiation*/ true,
1594 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001595 if (UD)
John McCalled976492009-12-04 22:46:56 +00001596 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1597
Anders Carlsson0d8df782009-08-29 19:37:28 +00001598 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001599}
1600
John McCallce3ff2b2009-08-25 22:02:44 +00001601Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001602 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001603 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001604 if (D->isInvalidDecl())
1605 return 0;
1606
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001607 return Instantiator.Visit(D);
1608}
1609
John McCalle29ba202009-08-20 01:44:21 +00001610/// \brief Instantiates a nested template parameter list in the current
1611/// instantiation context.
1612///
1613/// \param L The parameter list to instantiate
1614///
1615/// \returns NULL if there was an error
1616TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001617TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001618 // Get errors for all the parameters before bailing out.
1619 bool Invalid = false;
1620
1621 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001622 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001623 ParamVector Params;
1624 Params.reserve(N);
1625 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1626 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001627 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001628 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001629 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001630 }
1631
1632 // Clean up if we had an error.
1633 if (Invalid) {
1634 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1635 PI != PE; ++PI)
1636 if (*PI)
1637 (*PI)->Destroy(SemaRef.Context);
1638 return NULL;
1639 }
1640
1641 TemplateParameterList *InstL
1642 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1643 L->getLAngleLoc(), &Params.front(), N,
1644 L->getRAngleLoc());
1645 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001646}
John McCalle29ba202009-08-20 01:44:21 +00001647
Douglas Gregored9c0f92009-10-29 00:04:11 +00001648/// \brief Instantiate the declaration of a class template partial
1649/// specialization.
1650///
1651/// \param ClassTemplate the (instantiated) class template that is partially
1652// specialized by the instantiation of \p PartialSpec.
1653///
1654/// \param PartialSpec the (uninstantiated) class template partial
1655/// specialization that we are instantiating.
1656///
1657/// \returns true if there was an error, false otherwise.
1658bool
1659TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1660 ClassTemplateDecl *ClassTemplate,
1661 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001662 // Create a local instantiation scope for this class template partial
1663 // specialization, which will contain the instantiations of the template
1664 // parameters.
1665 Sema::LocalInstantiationScope Scope(SemaRef);
1666
Douglas Gregored9c0f92009-10-29 00:04:11 +00001667 // Substitute into the template parameters of the class template partial
1668 // specialization.
1669 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1670 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1671 if (!InstParams)
1672 return true;
1673
1674 // Substitute into the template arguments of the class template partial
1675 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001676 const TemplateArgumentLoc *PartialSpecTemplateArgs
1677 = PartialSpec->getTemplateArgsAsWritten();
1678 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1679
John McCalld5532b62009-11-23 01:53:49 +00001680 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001681 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001682 TemplateArgumentLoc Loc;
1683 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001684 return true;
John McCalld5532b62009-11-23 01:53:49 +00001685 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001686 }
1687
1688
1689 // Check that the template argument list is well-formed for this
1690 // class template.
1691 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1692 InstTemplateArgs.size());
1693 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1694 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001695 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001696 false,
1697 Converted))
1698 return true;
1699
1700 // Figure out where to insert this class template partial specialization
1701 // in the member template's set of class template partial specializations.
1702 llvm::FoldingSetNodeID ID;
1703 ClassTemplatePartialSpecializationDecl::Profile(ID,
1704 Converted.getFlatArguments(),
1705 Converted.flatSize(),
1706 SemaRef.Context);
1707 void *InsertPos = 0;
1708 ClassTemplateSpecializationDecl *PrevDecl
1709 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1710 InsertPos);
1711
1712 // Build the canonical type that describes the converted template
1713 // arguments of the class template partial specialization.
1714 QualType CanonType
1715 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1716 Converted.getFlatArguments(),
1717 Converted.flatSize());
1718
1719 // Build the fully-sugared type for this class template
1720 // specialization as the user wrote in the specialization
1721 // itself. This means that we'll pretty-print the type retrieved
1722 // from the specialization's declaration the way that the user
1723 // actually wrote the specialization, rather than formatting the
1724 // name based on the "canonical" representation used to store the
1725 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001726 TypeSourceInfo *WrittenTy
1727 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1728 TemplateName(ClassTemplate),
1729 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001730 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001731 CanonType);
1732
1733 if (PrevDecl) {
1734 // We've already seen a partial specialization with the same template
1735 // parameters and template arguments. This can happen, for example, when
1736 // substituting the outer template arguments ends up causing two
1737 // class template partial specializations of a member class template
1738 // to have identical forms, e.g.,
1739 //
1740 // template<typename T, typename U>
1741 // struct Outer {
1742 // template<typename X, typename Y> struct Inner;
1743 // template<typename Y> struct Inner<T, Y>;
1744 // template<typename Y> struct Inner<U, Y>;
1745 // };
1746 //
1747 // Outer<int, int> outer; // error: the partial specializations of Inner
1748 // // have the same signature.
1749 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1750 << WrittenTy;
1751 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1752 << SemaRef.Context.getTypeDeclType(PrevDecl);
1753 return true;
1754 }
1755
1756
1757 // Create the class template partial specialization declaration.
1758 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1759 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1760 PartialSpec->getLocation(),
1761 InstParams,
1762 ClassTemplate,
1763 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001764 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001765 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001766 0);
John McCallb6217662010-03-15 10:12:16 +00001767 // Substitute the nested name specifier, if any.
1768 if (SubstQualifier(PartialSpec, InstPartialSpec))
1769 return 0;
1770
Douglas Gregored9c0f92009-10-29 00:04:11 +00001771 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1772 InstPartialSpec->setTypeAsWritten(WrittenTy);
1773
1774 // Add this partial specialization to the set of class template partial
1775 // specializations.
1776 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1777 InsertPos);
1778 return false;
1779}
1780
John McCall21ef0fa2010-03-11 09:03:00 +00001781TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001782TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001783 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001784 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1785 assert(OldTInfo && "substituting function without type source info");
1786 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001787 TypeSourceInfo *NewTInfo
1788 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1789 D->getTypeSpecStartLoc(),
1790 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001791 if (!NewTInfo)
1792 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001793
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001794 if (NewTInfo != OldTInfo) {
1795 // Get parameters from the new type info.
1796 TypeLoc NewTL = NewTInfo->getTypeLoc();
1797 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1798 assert(NewProtoLoc && "Missing prototype?");
1799 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1800 Params.push_back(NewProtoLoc->getArg(i));
1801 } else {
1802 // The function type itself was not dependent and therefore no
1803 // substitution occurred. However, we still need to instantiate
1804 // the function parameters themselves.
1805 TypeLoc OldTL = OldTInfo->getTypeLoc();
1806 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL);
1807 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1808 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1809 if (!Parm)
1810 return 0;
1811 Params.push_back(Parm);
1812 }
1813 }
John McCall21ef0fa2010-03-11 09:03:00 +00001814 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001815}
1816
Mike Stump1eb44332009-09-09 15:08:12 +00001817/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001818/// declaration (New) from the corresponding fields of its template (Tmpl).
1819///
1820/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001821bool
1822TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001823 FunctionDecl *Tmpl) {
1824 if (Tmpl->isDeleted())
1825 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Douglas Gregorcca9e962009-07-01 22:01:06 +00001827 // If we are performing substituting explicitly-specified template arguments
1828 // or deduced template arguments into a function template and we reach this
1829 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001830 // to keeping the new function template specialization. We therefore
1831 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001832 // into a template instantiation for this specific function template
1833 // specialization, which is not a SFINAE context, so that we diagnose any
1834 // further errors in the declaration itself.
1835 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1836 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1837 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1838 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001839 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001840 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001841 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001842 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001843 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001844 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1845 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001846 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001847 }
1848 }
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001850 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1851 assert(Proto && "Function template without prototype?");
1852
1853 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1854 Proto->getNoReturnAttr()) {
1855 // The function has an exception specification or a "noreturn"
1856 // attribute. Substitute into each of the exception types.
1857 llvm::SmallVector<QualType, 4> Exceptions;
1858 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1859 // FIXME: Poor location information!
1860 QualType T
1861 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1862 New->getLocation(), New->getDeclName());
1863 if (T.isNull() ||
1864 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1865 continue;
1866
1867 Exceptions.push_back(T);
1868 }
1869
1870 // Rebuild the function type
1871
1872 const FunctionProtoType *NewProto
1873 = New->getType()->getAs<FunctionProtoType>();
1874 assert(NewProto && "Template instantiation without function prototype?");
1875 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1876 NewProto->arg_type_begin(),
1877 NewProto->getNumArgs(),
1878 NewProto->isVariadic(),
1879 NewProto->getTypeQuals(),
1880 Proto->hasExceptionSpec(),
1881 Proto->hasAnyExceptionSpec(),
1882 Exceptions.size(),
1883 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001884 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001885 }
1886
Douglas Gregore53060f2009-06-25 22:08:12 +00001887 return false;
1888}
1889
Douglas Gregor5545e162009-03-24 00:38:23 +00001890/// \brief Initializes common fields of an instantiated method
1891/// declaration (New) from the corresponding fields of its template
1892/// (Tmpl).
1893///
1894/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001895bool
1896TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001897 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001898 if (InitFunctionInstantiation(New, Tmpl))
1899 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Douglas Gregor5545e162009-03-24 00:38:23 +00001901 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1902 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001903 if (Tmpl->isVirtualAsWritten())
1904 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001905
1906 // FIXME: attributes
1907 // FIXME: New needs a pointer to Tmpl
1908 return false;
1909}
Douglas Gregora58861f2009-05-13 20:28:22 +00001910
1911/// \brief Instantiate the definition of the given function from its
1912/// template.
1913///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001914/// \param PointOfInstantiation the point at which the instantiation was
1915/// required. Note that this is not precisely a "point of instantiation"
1916/// for the function, but it's close.
1917///
Douglas Gregora58861f2009-05-13 20:28:22 +00001918/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001919/// function template specialization or member function of a class template
1920/// specialization.
1921///
1922/// \param Recursive if true, recursively instantiates any functions that
1923/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001924///
1925/// \param DefinitionRequired if true, then we are performing an explicit
1926/// instantiation where the body of the function is required. Complain if
1927/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001928void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001929 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001930 bool Recursive,
1931 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001932 if (Function->isInvalidDecl())
1933 return;
1934
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001935 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001937 // Never instantiate an explicit specialization.
1938 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1939 return;
1940
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001941 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001942 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001943 Stmt *Pattern = 0;
1944 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001945 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001946
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001947 if (!Pattern) {
1948 if (DefinitionRequired) {
1949 if (Function->getPrimaryTemplate())
1950 Diag(PointOfInstantiation,
1951 diag::err_explicit_instantiation_undefined_func_template)
1952 << Function->getPrimaryTemplate();
1953 else
1954 Diag(PointOfInstantiation,
1955 diag::err_explicit_instantiation_undefined_member)
1956 << 1 << Function->getDeclName() << Function->getDeclContext();
1957
1958 if (PatternDecl)
1959 Diag(PatternDecl->getLocation(),
1960 diag::note_explicit_instantiation_here);
1961 }
1962
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001963 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001964 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001965
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001966 // C++0x [temp.explicit]p9:
1967 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001968 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001969 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001970 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001971 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001972 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001973 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001975 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1976 if (Inst)
1977 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001978
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001979 // If we're performing recursive template instantiation, create our own
1980 // queue of pending implicit instantiations that we will instantiate later,
1981 // while we're still within our own instantiation context.
1982 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1983 if (Recursive)
1984 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001986 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1987
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001988 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001989 // recorded, unless we're actually a member function within a local
1990 // class, in which case we need to merge our results with the parent
1991 // scope (of the enclosing function).
1992 bool MergeWithParentScope = false;
1993 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1994 MergeWithParentScope = Rec->isLocalClass();
1995
1996 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001998 // Introduce the instantiated function parameters into the local
1999 // instantiation scope.
2000 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2001 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2002 Function->getParamDecl(I));
2003
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002004 // Enter the scope of this instantiation. We don't use
2005 // PushDeclContext because we don't have a scope.
2006 DeclContext *PreviousContext = CurContext;
2007 CurContext = Function;
2008
Mike Stump1eb44332009-09-09 15:08:12 +00002009 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00002010 getTemplateInstantiationArgs(Function);
2011
2012 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002013 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002014 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2015 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2016 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002017 }
2018
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002019 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002020 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002021
Douglas Gregor52604ab2009-09-11 21:19:12 +00002022 if (Body.isInvalid())
2023 Function->setInvalidDecl();
2024
Mike Stump1eb44332009-09-09 15:08:12 +00002025 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002026 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002027
John McCall0c01d182010-03-24 05:22:00 +00002028 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2029
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002030 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002031
2032 DeclGroupRef DG(Function);
2033 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Douglas Gregor60406be2010-01-16 22:29:39 +00002035 // This class may have local implicit instantiations that need to be
2036 // instantiation within this scope.
2037 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2038 Scope.Exit();
2039
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002040 if (Recursive) {
2041 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002042 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002043 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002045 // Restore the set of pending implicit instantiations.
2046 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2047 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002048}
2049
2050/// \brief Instantiate the definition of the given variable from its
2051/// template.
2052///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002053/// \param PointOfInstantiation the point at which the instantiation was
2054/// required. Note that this is not precisely a "point of instantiation"
2055/// for the function, but it's close.
2056///
2057/// \param Var the already-instantiated declaration of a static member
2058/// variable of a class template specialization.
2059///
2060/// \param Recursive if true, recursively instantiates any functions that
2061/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002062///
2063/// \param DefinitionRequired if true, then we are performing an explicit
2064/// instantiation where an out-of-line definition of the member variable
2065/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002066void Sema::InstantiateStaticDataMemberDefinition(
2067 SourceLocation PointOfInstantiation,
2068 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002069 bool Recursive,
2070 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002071 if (Var->isInvalidDecl())
2072 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor7caa6822009-07-24 20:34:43 +00002074 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002075 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002076 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002077 assert(Def->isStaticDataMember() && "Not a static data member?");
2078 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregor0d035142009-10-27 18:42:08 +00002080 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002081 // We did not find an out-of-line definition of this static data member,
2082 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002083 // instantiate this definition (or provide a specialization for it) in
2084 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002085 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002086 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002087 Diag(PointOfInstantiation,
2088 diag::err_explicit_instantiation_undefined_member)
2089 << 2 << Var->getDeclName() << Var->getDeclContext();
2090 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2091 }
2092
Douglas Gregor7caa6822009-07-24 20:34:43 +00002093 return;
2094 }
2095
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002096 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002097 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002098 return;
2099
2100 // C++0x [temp.explicit]p9:
2101 // Except for inline functions, other explicit instantiation declarations
2102 // have the effect of suppressing the implicit instantiation of the entity
2103 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002104 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002105 == TSK_ExplicitInstantiationDeclaration)
2106 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregor7caa6822009-07-24 20:34:43 +00002108 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2109 if (Inst)
2110 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Douglas Gregor7caa6822009-07-24 20:34:43 +00002112 // If we're performing recursive template instantiation, create our own
2113 // queue of pending implicit instantiations that we will instantiate later,
2114 // while we're still within our own instantiation context.
2115 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2116 if (Recursive)
2117 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Douglas Gregor7caa6822009-07-24 20:34:43 +00002119 // Enter the scope of this instantiation. We don't use
2120 // PushDeclContext because we don't have a scope.
2121 DeclContext *PreviousContext = CurContext;
2122 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002124 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002125 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002126 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002127 CurContext = PreviousContext;
2128
2129 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002130 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2131 assert(MSInfo && "Missing member specialization information?");
2132 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2133 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002134 DeclGroupRef DG(Var);
2135 Consumer.HandleTopLevelDecl(DG);
2136 }
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregor7caa6822009-07-24 20:34:43 +00002138 if (Recursive) {
2139 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002140 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002141 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Douglas Gregor7caa6822009-07-24 20:34:43 +00002143 // Restore the set of pending implicit instantiations.
2144 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002145 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002146}
Douglas Gregor815215d2009-05-27 05:35:12 +00002147
Anders Carlsson09025312009-08-29 05:16:22 +00002148void
2149Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2150 const CXXConstructorDecl *Tmpl,
2151 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Anders Carlsson09025312009-08-29 05:16:22 +00002153 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002154 bool AnyErrors = false;
2155
Anders Carlsson09025312009-08-29 05:16:22 +00002156 // Instantiate all the initializers.
2157 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002158 InitsEnd = Tmpl->init_end();
2159 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002160 CXXBaseOrMemberInitializer *Init = *Inits;
2161
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002162 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002163 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002164 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002166 // Instantiate the initializer.
2167 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2168 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2169 AnyErrors = true;
2170 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002171 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002172
Anders Carlsson09025312009-08-29 05:16:22 +00002173 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002174 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002175 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002176 TemplateArgs,
2177 Init->getSourceLocation(),
2178 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002179 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002180 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002181 New->setInvalidDecl();
2182 continue;
2183 }
2184
John McCalla93c9342009-12-07 02:54:59 +00002185 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002186 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002187 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002188 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002189 Init->getRParenLoc(),
2190 New->getParent());
2191 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002192 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002194 // Is this an anonymous union?
2195 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002196 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2197 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002198 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002199 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2200 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002201 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002202
2203 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002204 NewArgs.size(),
2205 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002206 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002207 Init->getRParenLoc());
2208 }
2209
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002210 if (NewInit.isInvalid()) {
2211 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002212 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002213 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002214 // FIXME: It would be nice if ASTOwningVector had a release function.
2215 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Anders Carlsson09025312009-08-29 05:16:22 +00002217 NewInits.push_back((MemInitTy *)NewInit.get());
2218 }
2219 }
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Anders Carlsson09025312009-08-29 05:16:22 +00002221 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002222 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002223 /*FIXME: ColonLoc */
2224 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002225 NewInits.data(), NewInits.size(),
2226 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002227}
2228
John McCall52a575a2009-08-29 08:11:13 +00002229// TODO: this could be templated if the various decl types used the
2230// same method name.
2231static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2232 ClassTemplateDecl *Instance) {
2233 Pattern = Pattern->getCanonicalDecl();
2234
2235 do {
2236 Instance = Instance->getCanonicalDecl();
2237 if (Pattern == Instance) return true;
2238 Instance = Instance->getInstantiatedFromMemberTemplate();
2239 } while (Instance);
2240
2241 return false;
2242}
2243
Douglas Gregor0d696532009-09-28 06:34:35 +00002244static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2245 FunctionTemplateDecl *Instance) {
2246 Pattern = Pattern->getCanonicalDecl();
2247
2248 do {
2249 Instance = Instance->getCanonicalDecl();
2250 if (Pattern == Instance) return true;
2251 Instance = Instance->getInstantiatedFromMemberTemplate();
2252 } while (Instance);
2253
2254 return false;
2255}
2256
Douglas Gregored9c0f92009-10-29 00:04:11 +00002257static bool
2258isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2259 ClassTemplatePartialSpecializationDecl *Instance) {
2260 Pattern
2261 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2262 do {
2263 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2264 Instance->getCanonicalDecl());
2265 if (Pattern == Instance)
2266 return true;
2267 Instance = Instance->getInstantiatedFromMember();
2268 } while (Instance);
2269
2270 return false;
2271}
2272
John McCall52a575a2009-08-29 08:11:13 +00002273static bool isInstantiationOf(CXXRecordDecl *Pattern,
2274 CXXRecordDecl *Instance) {
2275 Pattern = Pattern->getCanonicalDecl();
2276
2277 do {
2278 Instance = Instance->getCanonicalDecl();
2279 if (Pattern == Instance) return true;
2280 Instance = Instance->getInstantiatedFromMemberClass();
2281 } while (Instance);
2282
2283 return false;
2284}
2285
2286static bool isInstantiationOf(FunctionDecl *Pattern,
2287 FunctionDecl *Instance) {
2288 Pattern = Pattern->getCanonicalDecl();
2289
2290 do {
2291 Instance = Instance->getCanonicalDecl();
2292 if (Pattern == Instance) return true;
2293 Instance = Instance->getInstantiatedFromMemberFunction();
2294 } while (Instance);
2295
2296 return false;
2297}
2298
2299static bool isInstantiationOf(EnumDecl *Pattern,
2300 EnumDecl *Instance) {
2301 Pattern = Pattern->getCanonicalDecl();
2302
2303 do {
2304 Instance = Instance->getCanonicalDecl();
2305 if (Pattern == Instance) return true;
2306 Instance = Instance->getInstantiatedFromMemberEnum();
2307 } while (Instance);
2308
2309 return false;
2310}
2311
John McCalled976492009-12-04 22:46:56 +00002312static bool isInstantiationOf(UsingShadowDecl *Pattern,
2313 UsingShadowDecl *Instance,
2314 ASTContext &C) {
2315 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2316}
2317
2318static bool isInstantiationOf(UsingDecl *Pattern,
2319 UsingDecl *Instance,
2320 ASTContext &C) {
2321 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2322}
2323
John McCall7ba107a2009-11-18 02:36:19 +00002324static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2325 UsingDecl *Instance,
2326 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002327 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002328}
2329
2330static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002331 UsingDecl *Instance,
2332 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002333 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002334}
2335
John McCall52a575a2009-08-29 08:11:13 +00002336static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2337 VarDecl *Instance) {
2338 assert(Instance->isStaticDataMember());
2339
2340 Pattern = Pattern->getCanonicalDecl();
2341
2342 do {
2343 Instance = Instance->getCanonicalDecl();
2344 if (Pattern == Instance) return true;
2345 Instance = Instance->getInstantiatedFromStaticDataMember();
2346 } while (Instance);
2347
2348 return false;
2349}
2350
John McCalled976492009-12-04 22:46:56 +00002351// Other is the prospective instantiation
2352// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002353static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002354 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002355 if (UnresolvedUsingTypenameDecl *UUD
2356 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2357 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2358 return isInstantiationOf(UUD, UD, Ctx);
2359 }
2360 }
2361
2362 if (UnresolvedUsingValueDecl *UUD
2363 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002364 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2365 return isInstantiationOf(UUD, UD, Ctx);
2366 }
2367 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002368
Anders Carlsson0d8df782009-08-29 19:37:28 +00002369 return false;
2370 }
Mike Stump1eb44332009-09-09 15:08:12 +00002371
John McCall52a575a2009-08-29 08:11:13 +00002372 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2373 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002374
John McCall52a575a2009-08-29 08:11:13 +00002375 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2376 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002377
John McCall52a575a2009-08-29 08:11:13 +00002378 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2379 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002380
Douglas Gregor7caa6822009-07-24 20:34:43 +00002381 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002382 if (Var->isStaticDataMember())
2383 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2384
2385 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2386 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002387
Douglas Gregor0d696532009-09-28 06:34:35 +00002388 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2389 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2390
Douglas Gregored9c0f92009-10-29 00:04:11 +00002391 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2392 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2393 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2394 PartialSpec);
2395
Anders Carlssond8b285f2009-09-01 04:26:58 +00002396 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2397 if (!Field->getDeclName()) {
2398 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002399 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002400 cast<FieldDecl>(D);
2401 }
2402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCalled976492009-12-04 22:46:56 +00002404 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2405 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2406
2407 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2408 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2409
Douglas Gregor815215d2009-05-27 05:35:12 +00002410 return D->getDeclName() && isa<NamedDecl>(Other) &&
2411 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2412}
2413
2414template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002415static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002416 NamedDecl *D,
2417 ForwardIterator first,
2418 ForwardIterator last) {
2419 for (; first != last; ++first)
2420 if (isInstantiationOf(Ctx, D, *first))
2421 return cast<NamedDecl>(*first);
2422
2423 return 0;
2424}
2425
John McCall02cace72009-08-28 07:59:38 +00002426/// \brief Finds the instantiation of the given declaration context
2427/// within the current instantiation.
2428///
2429/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002430DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002431 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002432 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002433 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002434 return cast_or_null<DeclContext>(ID);
2435 } else return DC;
2436}
2437
Douglas Gregored961e72009-05-27 17:54:46 +00002438/// \brief Find the instantiation of the given declaration within the
2439/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002440///
2441/// This routine is intended to be used when \p D is a declaration
2442/// referenced from within a template, that needs to mapped into the
2443/// corresponding declaration within an instantiation. For example,
2444/// given:
2445///
2446/// \code
2447/// template<typename T>
2448/// struct X {
2449/// enum Kind {
2450/// KnownValue = sizeof(T)
2451/// };
2452///
2453/// bool getKind() const { return KnownValue; }
2454/// };
2455///
2456/// template struct X<int>;
2457/// \endcode
2458///
2459/// In the instantiation of X<int>::getKind(), we need to map the
2460/// EnumConstantDecl for KnownValue (which refers to
2461/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002462/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2463/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002464NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002465 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002466 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002467 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002468 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002469 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002470 // D is a local of some kind. Look into the map of local
2471 // declarations to their instantiations.
2472 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2473 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002474
Douglas Gregore95b4092009-09-16 18:34:49 +00002475 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2476 if (!Record->isDependentContext())
2477 return D;
2478
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002479 // If the RecordDecl is actually the injected-class-name or a
2480 // "templated" declaration for a class template, class template
2481 // partial specialization, or a member class of a class template,
2482 // substitute into the injected-class-name of the class template
2483 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002484 QualType T;
2485 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2486
2487 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002488 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002489 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2490 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002491 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002492
2493 // If we call SubstType with an InjectedClassNameType here we
2494 // can end up in an infinite loop.
2495 T = Context.getTypeDeclType(Record);
2496 assert(isa<InjectedClassNameType>(T) &&
2497 "type of partial specialization is not an InjectedClassNameType");
2498 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2499 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002500
2501 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002502 // Substitute into the injected-class-name to get the type
2503 // corresponding to the instantiation we want, which may also be
2504 // the current instantiation (if we're in a template
2505 // definition). This substitution should never fail, since we
2506 // know we can instantiate the injected-class-name or we
2507 // wouldn't have gotten to the injected-class-name!
2508
2509 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2510 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002511 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2512 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2513
2514 if (!T->isDependentType()) {
2515 assert(T->isRecordType() && "Instantiation must produce a record type");
2516 return T->getAs<RecordType>()->getDecl();
2517 }
2518
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002519 // We are performing "partial" template instantiation to create
2520 // the member declarations for the members of a class template
2521 // specialization. Therefore, D is actually referring to something
2522 // in the current instantiation. Look through the current
2523 // context, which contains actual instantiations, to find the
2524 // instantiation of the "current instantiation" that D refers
2525 // to.
2526 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002527 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002528 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002529 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002530 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002531 if (isInstantiationOf(ClassTemplate,
2532 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002533 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002534
2535 if (!DC->isDependentContext())
2536 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002537 }
2538
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002539 // We're performing "instantiation" of a member of the current
2540 // instantiation while we are type-checking the
2541 // definition. Compute the declaration context and return that.
2542 assert(!SawNonDependentContext &&
2543 "No dependent context while instantiating record");
2544 DeclContext *DC = computeDeclContext(T);
2545 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002546 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002547 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002548 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002549
Douglas Gregore95b4092009-09-16 18:34:49 +00002550 // Fall through to deal with other dependent record types (e.g.,
2551 // anonymous unions in class templates).
2552 }
John McCall52a575a2009-08-29 08:11:13 +00002553
Douglas Gregore95b4092009-09-16 18:34:49 +00002554 if (!ParentDC->isDependentContext())
2555 return D;
2556
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002557 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002558 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002559 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002560
Douglas Gregor815215d2009-05-27 05:35:12 +00002561 if (ParentDC != D->getDeclContext()) {
2562 // We performed some kind of instantiation in the parent context,
2563 // so now we need to look into the instantiated parent context to
2564 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002565
John McCall3cb0ebd2010-03-10 03:28:59 +00002566 // If our context used to be dependent, we may need to instantiate
2567 // it before performing lookup into that context.
2568 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002569 if (!Spec->isDependentContext()) {
2570 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002571 const RecordType *Tag = T->getAs<RecordType>();
2572 assert(Tag && "type of non-dependent record is not a RecordType");
2573 if (!Tag->isBeingDefined() &&
2574 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2575 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002576 }
2577 }
2578
Douglas Gregor815215d2009-05-27 05:35:12 +00002579 NamedDecl *Result = 0;
2580 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002581 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002582 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2583 } else {
2584 // Since we don't have a name for the entity we're looking for,
2585 // our only option is to walk through all of the declarations to
2586 // find that name. This will occur in a few cases:
2587 //
2588 // - anonymous struct/union within a template
2589 // - unnamed class/struct/union/enum within a template
2590 //
2591 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002592 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002593 ParentDC->decls_begin(),
2594 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
John McCall9f54ad42009-12-10 09:41:52 +00002597 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002598 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2599 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002600 && "Unable to find instantiation of declaration!");
2601
Douglas Gregor815215d2009-05-27 05:35:12 +00002602 D = Result;
2603 }
2604
Douglas Gregor815215d2009-05-27 05:35:12 +00002605 return D;
2606}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002607
Mike Stump1eb44332009-09-09 15:08:12 +00002608/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002609/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002610void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2611 while (!PendingLocalImplicitInstantiations.empty() ||
2612 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2613 PendingImplicitInstantiation Inst;
2614
2615 if (PendingLocalImplicitInstantiations.empty()) {
2616 Inst = PendingImplicitInstantiations.front();
2617 PendingImplicitInstantiations.pop_front();
2618 } else {
2619 Inst = PendingLocalImplicitInstantiations.front();
2620 PendingLocalImplicitInstantiations.pop_front();
2621 }
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Douglas Gregor7caa6822009-07-24 20:34:43 +00002623 // Instantiate function definitions
2624 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002625 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002626 Function->getLocation(), *this,
2627 Context.getSourceManager(),
2628 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002630 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002631 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002632 continue;
2633 }
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Douglas Gregor7caa6822009-07-24 20:34:43 +00002635 // Instantiate static data member definitions.
2636 VarDecl *Var = cast<VarDecl>(Inst.first);
2637 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002638
Chandler Carruth291b4412010-02-13 10:17:50 +00002639 // Don't try to instantiate declarations if the most recent redeclaration
2640 // is invalid.
2641 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2642 continue;
2643
2644 // Check if the most recent declaration has changed the specialization kind
2645 // and removed the need for implicit instantiation.
2646 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2647 case TSK_Undeclared:
2648 assert(false && "Cannot instantitiate an undeclared specialization.");
2649 case TSK_ExplicitInstantiationDeclaration:
2650 case TSK_ExplicitInstantiationDefinition:
2651 case TSK_ExplicitSpecialization:
2652 continue; // No longer need implicit instantiation.
2653 case TSK_ImplicitInstantiation:
2654 break;
2655 }
2656
Mike Stump1eb44332009-09-09 15:08:12 +00002657 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002658 Var->getLocation(), *this,
2659 Context.getSourceManager(),
2660 "instantiating static data member "
2661 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Douglas Gregor7caa6822009-07-24 20:34:43 +00002663 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002664 }
2665}
John McCall0c01d182010-03-24 05:22:00 +00002666
2667void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2668 const MultiLevelTemplateArgumentList &TemplateArgs) {
2669 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2670 E = Pattern->ddiag_end(); I != E; ++I) {
2671 DependentDiagnostic *DD = *I;
2672
2673 switch (DD->getKind()) {
2674 case DependentDiagnostic::Access:
2675 HandleDependentAccessCheck(*DD, TemplateArgs);
2676 break;
2677 }
2678 }
2679}