blob: a81e5e95f895b5d30d138b2412e579725107072c [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);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000368
369 if (Owner->isFunctionOrMethod())
370 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000371 }
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000373 // Link instantiations of static data members back to the template from
374 // which they were instantiated.
375 if (Var->isStaticDataMember())
376 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000377 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000378
Douglas Gregor60c93c92010-02-09 07:26:29 +0000379 if (Var->getAnyInitializer()) {
380 // We already have an initializer in the class.
381 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000382 if (Var->isStaticDataMember() && !D->isOutOfLine())
383 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
384 else
385 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
386
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000387 // Instantiate the initializer.
388 SourceLocation LParenLoc, RParenLoc;
389 llvm::SmallVector<SourceLocation, 4> CommaLocs;
390 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
391 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
392 CommaLocs, InitArgs, RParenLoc)) {
393 // Attach the initializer to the declaration.
394 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000396 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000398 move_arg(InitArgs),
399 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000400 RParenLoc);
401 } else if (InitArgs.size() == 1) {
402 Expr *Init = (Expr*)(InitArgs.take()[0]);
403 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
404 SemaRef.Owned(Init),
405 false);
406 } else {
407 assert(InitArgs.size() == 0);
408 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000409 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000410 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000411 // FIXME: Not too happy about invalidating the declaration
412 // because of a bogus initializer.
413 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000414 }
415
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000416 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000417 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
418 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000419
420 return Var;
421}
422
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000423Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
424 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000425 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000426 if (DI->getType()->isDependentType()) {
427 DI = SemaRef.SubstType(DI, TemplateArgs,
428 D->getLocation(), D->getDeclName());
429 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000430 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000431 Invalid = true;
432 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000433 // C++ [temp.arg.type]p3:
434 // If a declaration acquires a function type through a type
435 // dependent on a template-parameter and this causes a
436 // declaration that does not use the syntactic form of a
437 // function declarator to have function type, the program is
438 // ill-formed.
439 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000440 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 Invalid = true;
442 }
443 }
444
445 Expr *BitWidth = D->getBitWidth();
446 if (Invalid)
447 BitWidth = 0;
448 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000449 // The bit-width expression is not potentially evaluated.
450 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000452 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000453 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 if (InstantiatedBitWidth.isInvalid()) {
455 Invalid = true;
456 BitWidth = 0;
457 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000458 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459 }
460
John McCall07fb6be2009-10-22 23:33:21 +0000461 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
462 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000463 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464 D->getLocation(),
465 D->isMutable(),
466 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000467 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000468 D->getAccess(),
469 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000470 if (!Field) {
471 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000472 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000475 InstantiateAttrs(D, Field);
476
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000477 if (Invalid)
478 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000480 if (!Field->getDeclName()) {
481 // Keep track of where this decl came from.
482 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000485 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000486 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000487 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488
489 return Field;
490}
491
John McCall02cace72009-08-28 07:59:38 +0000492Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000493 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000494 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000495 if (TypeSourceInfo *Ty = D->getFriendType()) {
496 TypeSourceInfo *InstTy =
497 SemaRef.SubstType(Ty, TemplateArgs,
498 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000500 return 0;
John McCall02cace72009-08-28 07:59:38 +0000501
Douglas Gregor06245bf2010-04-07 17:57:12 +0000502 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
503 if (!FD)
504 return 0;
505
506 FD->setAccess(AS_public);
507 Owner->addDecl(FD);
508 return FD;
509 }
510
511 NamedDecl *ND = D->getFriendDecl();
512 assert(ND && "friend decl must be a decl or a type!");
513
John McCallaf2094e2010-04-08 09:05:18 +0000514 // All of the Visit implementations for the various potential friend
515 // declarations have to be carefully written to work for friend
516 // objects, with the most important detail being that the target
517 // decl should almost certainly not be placed in Owner.
518 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000519 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
John McCall02cace72009-08-28 07:59:38 +0000521 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000522 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
523 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000524 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000525 Owner->addDecl(FD);
526 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000527}
528
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000529Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
530 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregorac7610d2009-06-22 20:57:11 +0000532 // The expression in a static assertion is not potentially evaluated.
533 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000536 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537 if (InstantiatedAssertExpr.isInvalid())
538 return 0;
539
Douglas Gregor43d9d922009-08-08 01:41:12 +0000540 OwningExprResult Message(SemaRef, D->getMessage());
541 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000542 Decl *StaticAssert
543 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544 move(InstantiatedAssertExpr),
545 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000546 return StaticAssert;
547}
548
549Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000551 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000552 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000553 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000554 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000555 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000556 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000557 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000558 Enum->startDefinition();
559
Douglas Gregor96084f12010-03-01 19:00:07 +0000560 if (D->getDeclContext()->isFunctionOrMethod())
561 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
562
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000563 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564
565 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000566 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
567 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000568 EC != ECEnd; ++EC) {
569 // The specified value for the enumerator.
570 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000571 if (Expr *UninstValue = EC->getInitExpr()) {
572 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000573 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000574 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000575
John McCallce3ff2b2009-08-25 22:02:44 +0000576 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000577 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000578
579 // Drop the initial value and continue.
580 bool isInvalid = false;
581 if (Value.isInvalid()) {
582 Value = SemaRef.Owned((Expr *)0);
583 isInvalid = true;
584 }
585
Mike Stump1eb44332009-09-09 15:08:12 +0000586 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000587 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
588 EC->getLocation(), EC->getIdentifier(),
589 move(Value));
590
591 if (isInvalid) {
592 if (EnumConst)
593 EnumConst->setInvalidDecl();
594 Enum->setInvalidDecl();
595 }
596
597 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000598 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000599 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000600 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000601 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000602
603 if (D->getDeclContext()->isFunctionOrMethod()) {
604 // If the enumeration is within a function or method, record the enum
605 // constant as a local.
606 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
607 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000608 }
609 }
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000611 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000612 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000613 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
614 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000615 &Enumerators[0], Enumerators.size(),
616 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000617
618 return Enum;
619}
620
Douglas Gregor6477b692009-03-25 15:04:13 +0000621Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
622 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
623 return 0;
624}
625
John McCalle29ba202009-08-20 01:44:21 +0000626Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000627 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
628
Douglas Gregor550d9b22009-10-31 17:21:17 +0000629 // Create a local instantiation scope for this class template, which
630 // will contain the instantiations of the template parameters.
631 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000632 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000633 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000634 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000635 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000636
637 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000638
639 // Instantiate the qualifier. We have to do this first in case
640 // we're a friend declaration, because if we are then we need to put
641 // the new declaration in the appropriate context.
642 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
643 if (Qualifier) {
644 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
645 Pattern->getQualifierRange(),
646 TemplateArgs);
647 if (!Qualifier) return 0;
648 }
649
650 CXXRecordDecl *PrevDecl = 0;
651 ClassTemplateDecl *PrevClassTemplate = 0;
652
653 // If this isn't a friend, then it's a member template, in which
654 // case we just want to build the instantiation in the
655 // specialization. If it is a friend, we want to build it in
656 // the appropriate context.
657 DeclContext *DC = Owner;
658 if (isFriend) {
659 if (Qualifier) {
660 CXXScopeSpec SS;
661 SS.setScopeRep(Qualifier);
662 SS.setRange(Pattern->getQualifierRange());
663 DC = SemaRef.computeDeclContext(SS);
664 if (!DC) return 0;
665 } else {
666 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
667 Pattern->getDeclContext(),
668 TemplateArgs);
669 }
670
671 // Look for a previous declaration of the template in the owning
672 // context.
673 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
674 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
675 SemaRef.LookupQualifiedName(R, DC);
676
677 if (R.isSingleResult()) {
678 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
679 if (PrevClassTemplate)
680 PrevDecl = PrevClassTemplate->getTemplatedDecl();
681 }
682
683 if (!PrevClassTemplate && Qualifier) {
684 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000685 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
686 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000687 return 0;
688 }
689
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000690 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000691 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000692 bool Complain = true;
693
694 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
695 // template for struct std::tr1::__detail::_Map_base, where the
696 // template parameters of the friend declaration don't match the
697 // template parameters of the original declaration. In this one
698 // case, we don't complain about the ill-formed friend
699 // declaration.
700 if (isFriend && Pattern->getIdentifier() &&
701 Pattern->getIdentifier()->isStr("_Map_base") &&
702 DC->isNamespace() &&
703 cast<NamespaceDecl>(DC)->getIdentifier() &&
704 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
705 DeclContext *DCParent = DC->getParent();
706 if (DCParent->isNamespace() &&
707 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
708 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
709 DeclContext *DCParent2 = DCParent->getParent();
710 if (DCParent2->isNamespace() &&
711 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
712 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
713 DCParent2->getParent()->isTranslationUnit())
714 Complain = false;
715 }
716 }
717
John McCall93ba8572010-03-25 06:39:04 +0000718 TemplateParameterList *PrevParams
719 = PrevClassTemplate->getTemplateParameters();
720
721 // Make sure the parameter lists match.
722 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000723 Complain,
724 Sema::TPL_TemplateMatch)) {
725 if (Complain)
726 return 0;
727
728 AdoptedPreviousTemplateParams = true;
729 InstParams = PrevParams;
730 }
John McCall93ba8572010-03-25 06:39:04 +0000731
732 // Do some additional validation, then merge default arguments
733 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000734 if (!AdoptedPreviousTemplateParams &&
735 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000736 Sema::TPC_ClassTemplate))
737 return 0;
738 }
739 }
740
John McCalle29ba202009-08-20 01:44:21 +0000741 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000742 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000743 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000744 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000745 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000746
John McCall93ba8572010-03-25 06:39:04 +0000747 if (Qualifier)
748 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000749
John McCalle29ba202009-08-20 01:44:21 +0000750 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000751 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
752 D->getIdentifier(), InstParams, RecordInst,
753 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000754 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000755
John McCall93ba8572010-03-25 06:39:04 +0000756 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000757 if (PrevClassTemplate)
758 Inst->setAccess(PrevClassTemplate->getAccess());
759 else
760 Inst->setAccess(D->getAccess());
761
John McCall93ba8572010-03-25 06:39:04 +0000762 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
763 // TODO: do we want to track the instantiation progeny of this
764 // friend target decl?
765 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000766 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000767 Inst->setInstantiatedFromMemberTemplate(D);
768 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000769
770 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000771 SemaRef.Context.getInjectedClassNameType(RecordInst,
772 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000773
Douglas Gregor259571e2009-10-30 22:42:42 +0000774 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000775 if (isFriend) {
776 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000777 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000778 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000779
John McCalle29ba202009-08-20 01:44:21 +0000780 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000781
Douglas Gregored9c0f92009-10-29 00:04:11 +0000782 // Instantiate all of the partial specializations of this member class
783 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000784 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
785 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000786 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
787 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
788
John McCalle29ba202009-08-20 01:44:21 +0000789 return Inst;
790}
791
Douglas Gregord60e1052009-08-27 16:57:43 +0000792Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000793TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
794 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000795 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
796
797 // Lookup the already-instantiated declaration in the instantiation
798 // of the class template and return that.
799 DeclContext::lookup_result Found
800 = Owner->lookup(ClassTemplate->getDeclName());
801 if (Found.first == Found.second)
802 return 0;
803
804 ClassTemplateDecl *InstClassTemplate
805 = dyn_cast<ClassTemplateDecl>(*Found.first);
806 if (!InstClassTemplate)
807 return 0;
808
809 Decl *DCanon = D->getCanonicalDecl();
810 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
811 P = InstClassTemplate->getPartialSpecializations().begin(),
812 PEnd = InstClassTemplate->getPartialSpecializations().end();
813 P != PEnd; ++P) {
814 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
815 return &*P;
816 }
817
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000818 return 0;
819}
820
821Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000822TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000823 // Create a local instantiation scope for this function template, which
824 // will contain the instantiations of the template parameters and then get
825 // merged with the local instantiation scope for the function template
826 // itself.
827 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000828
Douglas Gregord60e1052009-08-27 16:57:43 +0000829 TemplateParameterList *TempParams = D->getTemplateParameters();
830 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000831 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000832 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000833
Douglas Gregora735b202009-10-13 14:39:41 +0000834 FunctionDecl *Instantiated = 0;
835 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
836 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
837 InstParams));
838 else
839 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
840 D->getTemplatedDecl(),
841 InstParams));
842
843 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000844 return 0;
845
John McCall46460a62010-01-20 21:53:11 +0000846 Instantiated->setAccess(D->getAccess());
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000849 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000850 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000851 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000852 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000853 assert(InstTemplate &&
854 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000855
John McCallb1a56e72010-03-26 23:10:15 +0000856 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
857
John McCalle976ffe2009-12-14 23:19:40 +0000858 // Link the instantiation back to the pattern *unless* this is a
859 // non-definition friend declaration.
860 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000861 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000862 InstTemplate->setInstantiatedFromMemberTemplate(D);
863
John McCallb1a56e72010-03-26 23:10:15 +0000864 // Make declarations visible in the appropriate context.
865 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000866 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000867
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 return InstTemplate;
869}
870
Douglas Gregord475b8d2009-03-25 21:17:03 +0000871Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
872 CXXRecordDecl *PrevDecl = 0;
873 if (D->isInjectedClassName())
874 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000875 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000876 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
877 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000878 TemplateArgs);
879 if (!Prev) return 0;
880 PrevDecl = cast<CXXRecordDecl>(Prev);
881 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000882
883 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000884 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000885 D->getLocation(), D->getIdentifier(),
886 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000887
888 // Substitute the nested name specifier, if any.
889 if (SubstQualifier(D, Record))
890 return 0;
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000893 // FIXME: Check against AS_none is an ugly hack to work around the issue that
894 // the tag decls introduced by friend class declarations don't have an access
895 // specifier. Remove once this area of the code gets sorted out.
896 if (D->getAccess() != AS_none)
897 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000898 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000899 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000900
John McCall02cace72009-08-28 07:59:38 +0000901 // If the original function was part of a friend declaration,
902 // inherit its namespace state.
903 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
904 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
905
Anders Carlssond8b285f2009-09-01 04:26:58 +0000906 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
907
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000908 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000909 return Record;
910}
911
John McCall02cace72009-08-28 07:59:38 +0000912/// Normal class members are of more specific types and therefore
913/// don't make it here. This function serves two purposes:
914/// 1) instantiating function templates
915/// 2) substituting friend declarations
916/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000917Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000918 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000919 // Check whether there is already a function template specialization for
920 // this declaration.
921 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
922 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000923 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000924 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000925 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000926 TemplateArgs.getInnermost().getFlatArgumentList(),
927 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000928 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000929
930 FunctionTemplateSpecializationInfo *Info
931 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000932 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregor127102b2009-06-29 20:59:39 +0000934 // If we already have a function template specialization, return it.
935 if (Info)
936 return Info->Function;
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
John McCallb0cb0222010-03-27 05:57:59 +0000939 bool isFriend;
940 if (FunctionTemplate)
941 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
942 else
943 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
944
Douglas Gregor79c22782010-01-16 20:21:20 +0000945 bool MergeWithParentScope = (TemplateParams != 0) ||
946 !(isa<Decl>(Owner) &&
947 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
948 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Douglas Gregore53060f2009-06-25 22:08:12 +0000950 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000951 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
952 TInfo = SubstFunctionType(D, Params);
953 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000954 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000955 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000956
John McCalld325daa2010-03-26 04:53:08 +0000957 NestedNameSpecifier *Qualifier = D->getQualifier();
958 if (Qualifier) {
959 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
960 D->getQualifierRange(),
961 TemplateArgs);
962 if (!Qualifier) return 0;
963 }
964
John McCall68b6b872010-02-06 01:50:47 +0000965 // If we're instantiating a local function declaration, put the result
966 // in the owner; otherwise we need to find the instantiated context.
967 DeclContext *DC;
968 if (D->getDeclContext()->isFunctionOrMethod())
969 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000970 else if (isFriend && Qualifier) {
971 CXXScopeSpec SS;
972 SS.setScopeRep(Qualifier);
973 SS.setRange(D->getQualifierRange());
974 DC = SemaRef.computeDeclContext(SS);
975 if (!DC) return 0;
976 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000977 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
978 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000979 }
John McCall68b6b872010-02-06 01:50:47 +0000980
John McCall02cace72009-08-28 07:59:38 +0000981 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000982 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000983 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000984 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000985 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000986
John McCalld325daa2010-03-26 04:53:08 +0000987 if (Qualifier)
988 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000989
John McCallb1a56e72010-03-26 23:10:15 +0000990 DeclContext *LexicalDC = Owner;
991 if (!isFriend && D->isOutOfLine()) {
992 assert(D->getDeclContext()->isFileContext());
993 LexicalDC = D->getDeclContext();
994 }
995
996 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregore53060f2009-06-25 22:08:12 +0000998 // Attach the parameters
999 for (unsigned P = 0; P < Params.size(); ++P)
1000 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001001 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001002
Douglas Gregora735b202009-10-13 14:39:41 +00001003 if (TemplateParams) {
1004 // Our resulting instantiation is actually a function template, since we
1005 // are substituting only the outer template parameters. For example, given
1006 //
1007 // template<typename T>
1008 // struct X {
1009 // template<typename U> friend void f(T, U);
1010 // };
1011 //
1012 // X<int> x;
1013 //
1014 // We are instantiating the friend function template "f" within X<int>,
1015 // which means substituting int for T, but leaving "f" as a friend function
1016 // template.
1017 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001018 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001019 Function->getLocation(),
1020 Function->getDeclName(),
1021 TemplateParams, Function);
1022 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001023
1024 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001025
1026 if (isFriend && D->isThisDeclarationADefinition()) {
1027 // TODO: should we remember this connection regardless of whether
1028 // the friend declaration provided a body?
1029 FunctionTemplate->setInstantiatedFromMemberTemplate(
1030 D->getDescribedFunctionTemplate());
1031 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001032 } else if (FunctionTemplate) {
1033 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001034 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001035 &TemplateArgs.getInnermost(),
1036 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001037 } else if (isFriend && D->isThisDeclarationADefinition()) {
1038 // TODO: should we remember this connection regardless of whether
1039 // the friend declaration provided a body?
1040 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001041 }
Douglas Gregora735b202009-10-13 14:39:41 +00001042
Douglas Gregore53060f2009-06-25 22:08:12 +00001043 if (InitFunctionInstantiation(Function, D))
1044 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregore53060f2009-06-25 22:08:12 +00001046 bool Redeclaration = false;
1047 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001048 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001049
John McCall68263142009-11-18 22:49:29 +00001050 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1051 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1052
John McCallaf2094e2010-04-08 09:05:18 +00001053 if (DependentFunctionTemplateSpecializationInfo *Info
1054 = D->getDependentSpecializationInfo()) {
1055 assert(isFriend && "non-friend has dependent specialization info?");
1056
1057 // This needs to be set now for future sanity.
1058 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1059
1060 // Instantiate the explicit template arguments.
1061 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1062 Info->getRAngleLoc());
1063 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1064 TemplateArgumentLoc Loc;
1065 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1066 return 0;
1067
1068 ExplicitArgs.addArgument(Loc);
1069 }
1070
1071 // Map the candidate templates to their instantiations.
1072 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1073 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1074 Info->getTemplate(I),
1075 TemplateArgs);
1076 if (!Temp) return 0;
1077
1078 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1079 }
1080
1081 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1082 &ExplicitArgs,
1083 Previous))
1084 Function->setInvalidDecl();
1085
1086 isExplicitSpecialization = true;
1087
1088 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001089 // Look only into the namespace where the friend would be declared to
1090 // find a previous declaration. This is the innermost enclosing namespace,
1091 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001092 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001093
Douglas Gregora735b202009-10-13 14:39:41 +00001094 // In C++, the previous declaration we find might be a tag type
1095 // (class or enum). In this case, the new declaration will hide the
1096 // tag type. Note that this does does not apply if we're declaring a
1097 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001098 if (Previous.isSingleTagDecl())
1099 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001100 }
1101
John McCall9f54ad42009-12-10 09:41:52 +00001102 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001103 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001104 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001105
John McCall76d32642010-04-24 01:30:58 +00001106 NamedDecl *PrincipalDecl = (TemplateParams
1107 ? cast<NamedDecl>(FunctionTemplate)
1108 : Function);
1109
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // If the original function was part of a friend declaration,
1111 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001112 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001113 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001114 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001115 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001116 else
Douglas Gregora735b202009-10-13 14:39:41 +00001117 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001118
1119 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1120 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001121 }
1122
John McCall76d32642010-04-24 01:30:58 +00001123 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1124 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1125 PrincipalDecl->setNonMemberOperator();
1126
Douglas Gregore53060f2009-06-25 22:08:12 +00001127 return Function;
1128}
1129
Douglas Gregord60e1052009-08-27 16:57:43 +00001130Decl *
1131TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1132 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001133 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1134 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001135 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001136 // We are creating a function template specialization from a function
1137 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001138 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001139 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001140 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001141 TemplateArgs.getInnermost().getFlatArgumentList(),
1142 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001143 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001144
1145 FunctionTemplateSpecializationInfo *Info
1146 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001147 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Douglas Gregor6b906862009-08-21 00:16:32 +00001149 // If we already have a function template specialization, return it.
1150 if (Info)
1151 return Info->Function;
1152 }
1153
John McCallb0cb0222010-03-27 05:57:59 +00001154 bool isFriend;
1155 if (FunctionTemplate)
1156 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1157 else
1158 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1159
Douglas Gregor79c22782010-01-16 20:21:20 +00001160 bool MergeWithParentScope = (TemplateParams != 0) ||
1161 !(isa<Decl>(Owner) &&
1162 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1163 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001164
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001165 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001166 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1167 TInfo = SubstFunctionType(D, Params);
1168 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001169 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001170 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001171
John McCallb0cb0222010-03-27 05:57:59 +00001172 NestedNameSpecifier *Qualifier = D->getQualifier();
1173 if (Qualifier) {
1174 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1175 D->getQualifierRange(),
1176 TemplateArgs);
1177 if (!Qualifier) return 0;
1178 }
1179
1180 DeclContext *DC = Owner;
1181 if (isFriend) {
1182 if (Qualifier) {
1183 CXXScopeSpec SS;
1184 SS.setScopeRep(Qualifier);
1185 SS.setRange(D->getQualifierRange());
1186 DC = SemaRef.computeDeclContext(SS);
1187 } else {
1188 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1189 D->getDeclContext(),
1190 TemplateArgs);
1191 }
1192 if (!DC) return 0;
1193 }
1194
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001195 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001196 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001197 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregordec06662009-08-21 18:42:58 +00001199 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001200 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001201 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1202 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1203 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001204 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1205 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001206 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001207 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001208 Constructor->isInlineSpecified(),
1209 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001210 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1211 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1212 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1213 SemaRef.Context.getCanonicalType(ClassTy));
1214 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1215 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001216 T, Destructor->isInlineSpecified(),
1217 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001218 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001220 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001221 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001222 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1223 ConvTy);
1224 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1225 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001226 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001227 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001228 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001229 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001230 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001231 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001232 D->isStatic(),
1233 D->getStorageClassAsWritten(),
1234 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001235 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001236
John McCallb0cb0222010-03-27 05:57:59 +00001237 if (Qualifier)
1238 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001239
Douglas Gregord60e1052009-08-27 16:57:43 +00001240 if (TemplateParams) {
1241 // Our resulting instantiation is actually a function template, since we
1242 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001243 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001244 // template<typename T>
1245 // struct X {
1246 // template<typename U> void f(T, U);
1247 // };
1248 //
1249 // X<int> x;
1250 //
1251 // We are instantiating the member template "f" within X<int>, which means
1252 // substituting int for T, but leaving "f" as a member function template.
1253 // Build the function template itself.
1254 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1255 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001256 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001257 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001258 if (isFriend) {
1259 FunctionTemplate->setLexicalDeclContext(Owner);
1260 FunctionTemplate->setObjectOfFriendDecl(true);
1261 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001262 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001263 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001264 } else if (FunctionTemplate) {
1265 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001266 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001267 &TemplateArgs.getInnermost(),
1268 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001269 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001270 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001271 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001272 }
1273
Mike Stump1eb44332009-09-09 15:08:12 +00001274 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001275 // out-of-line, the instantiation will have the same lexical
1276 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001277 if (isFriend) {
1278 Method->setLexicalDeclContext(Owner);
1279 Method->setObjectOfFriendDecl(true);
1280 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001281 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregor5545e162009-03-24 00:38:23 +00001283 // Attach the parameters
1284 for (unsigned P = 0; P < Params.size(); ++P)
1285 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001286 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001287
1288 if (InitMethodInstantiation(Method, D))
1289 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001290
John McCall68263142009-11-18 22:49:29 +00001291 LookupResult Previous(SemaRef, Name, SourceLocation(),
1292 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCallb0cb0222010-03-27 05:57:59 +00001294 if (!FunctionTemplate || TemplateParams || isFriend) {
1295 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Douglas Gregordec06662009-08-21 18:42:58 +00001297 // In C++, the previous declaration we find might be a tag type
1298 // (class or enum). In this case, the new declaration will hide the
1299 // tag type. Note that this does does not apply if we're declaring a
1300 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001301 if (Previous.isSingleTagDecl())
1302 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001303 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001304
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001305 bool Redeclaration = false;
1306 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001307 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001308 /*FIXME:*/OverloadableAttrRequired);
1309
Douglas Gregor4ba31362009-12-01 17:24:26 +00001310 if (D->isPure())
1311 SemaRef.CheckPureMethod(Method, SourceRange());
1312
John McCall46460a62010-01-20 21:53:11 +00001313 Method->setAccess(D->getAccess());
1314
John McCallb0cb0222010-03-27 05:57:59 +00001315 if (FunctionTemplate) {
1316 // If there's a function template, let our caller handle it.
1317 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1318 // Don't hide a (potentially) valid declaration with an invalid one.
1319 } else {
1320 NamedDecl *DeclToAdd = (TemplateParams
1321 ? cast<NamedDecl>(FunctionTemplate)
1322 : Method);
1323 if (isFriend)
1324 Record->makeDeclVisibleInContext(DeclToAdd);
1325 else
1326 Owner->addDecl(DeclToAdd);
1327 }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001329 return Method;
1330}
1331
Douglas Gregor615c5d42009-03-24 16:43:20 +00001332Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001333 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001334}
1335
Douglas Gregor03b2b072009-03-24 00:15:49 +00001336Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001337 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001338}
1339
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001340Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001341 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001342}
1343
Douglas Gregor6477b692009-03-25 15:04:13 +00001344ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001345 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001346}
1347
John McCalle29ba202009-08-20 01:44:21 +00001348Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1349 TemplateTypeParmDecl *D) {
1350 // TODO: don't always clone when decls are refcounted.
1351 const Type* T = D->getTypeForDecl();
1352 assert(T->isTemplateTypeParmType());
1353 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001354
John McCalle29ba202009-08-20 01:44:21 +00001355 TemplateTypeParmDecl *Inst =
1356 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001357 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001358 TTPT->getName(),
1359 D->wasDeclaredWithTypename(),
1360 D->isParameterPack());
1361
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001362 if (D->hasDefaultArgument())
1363 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001364
Douglas Gregor550d9b22009-10-31 17:21:17 +00001365 // Introduce this template parameter's instantiation into the instantiation
1366 // scope.
1367 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1368
John McCalle29ba202009-08-20 01:44:21 +00001369 return Inst;
1370}
1371
Douglas Gregor33642df2009-10-23 23:25:44 +00001372Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1373 NonTypeTemplateParmDecl *D) {
1374 // Substitute into the type of the non-type template parameter.
1375 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001376 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001377 if (DI) {
1378 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1379 D->getDeclName());
1380 if (DI) T = DI->getType();
1381 } else {
1382 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1383 D->getDeclName());
1384 DI = 0;
1385 }
1386 if (T.isNull())
1387 return 0;
1388
1389 // Check that this type is acceptable for a non-type template parameter.
1390 bool Invalid = false;
1391 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1392 if (T.isNull()) {
1393 T = SemaRef.Context.IntTy;
1394 Invalid = true;
1395 }
1396
1397 NonTypeTemplateParmDecl *Param
1398 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1399 D->getDepth() - 1, D->getPosition(),
1400 D->getIdentifier(), T, DI);
1401 if (Invalid)
1402 Param->setInvalidDecl();
1403
1404 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001405
1406 // Introduce this template parameter's instantiation into the instantiation
1407 // scope.
1408 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001409 return Param;
1410}
1411
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001412Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001413TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1414 TemplateTemplateParmDecl *D) {
1415 // Instantiate the template parameter list of the template template parameter.
1416 TemplateParameterList *TempParams = D->getTemplateParameters();
1417 TemplateParameterList *InstParams;
1418 {
1419 // Perform the actual substitution of template parameters within a new,
1420 // local instantiation scope.
1421 Sema::LocalInstantiationScope Scope(SemaRef);
1422 InstParams = SubstTemplateParams(TempParams);
1423 if (!InstParams)
1424 return NULL;
1425 }
1426
1427 // Build the template template parameter.
1428 TemplateTemplateParmDecl *Param
1429 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1430 D->getDepth() - 1, D->getPosition(),
1431 D->getIdentifier(), InstParams);
1432 Param->setDefaultArgument(D->getDefaultArgument());
1433
1434 // Introduce this template parameter's instantiation into the instantiation
1435 // scope.
1436 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1437
1438 return Param;
1439}
1440
Douglas Gregor48c32a72009-11-17 06:07:40 +00001441Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1442 // Using directives are never dependent, so they require no explicit
1443
1444 UsingDirectiveDecl *Inst
1445 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1446 D->getNamespaceKeyLocation(),
1447 D->getQualifierRange(), D->getQualifier(),
1448 D->getIdentLocation(),
1449 D->getNominatedNamespace(),
1450 D->getCommonAncestor());
1451 Owner->addDecl(Inst);
1452 return Inst;
1453}
1454
John McCalled976492009-12-04 22:46:56 +00001455Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1456 // The nested name specifier is non-dependent, so no transformation
1457 // is required.
1458
John McCall9f54ad42009-12-10 09:41:52 +00001459 // We only need to do redeclaration lookups if we're in a class
1460 // scope (in fact, it's not really even possible in non-class
1461 // scopes).
1462 bool CheckRedeclaration = Owner->isRecord();
1463
1464 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1465 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1466
John McCalled976492009-12-04 22:46:56 +00001467 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1468 D->getLocation(),
1469 D->getNestedNameRange(),
1470 D->getUsingLocation(),
1471 D->getTargetNestedNameDecl(),
1472 D->getDeclName(),
1473 D->isTypeName());
1474
1475 CXXScopeSpec SS;
1476 SS.setScopeRep(D->getTargetNestedNameDecl());
1477 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001478
1479 if (CheckRedeclaration) {
1480 Prev.setHideTags(false);
1481 SemaRef.LookupQualifiedName(Prev, Owner);
1482
1483 // Check for invalid redeclarations.
1484 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1485 D->isTypeName(), SS,
1486 D->getLocation(), Prev))
1487 NewUD->setInvalidDecl();
1488
1489 }
1490
1491 if (!NewUD->isInvalidDecl() &&
1492 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001493 D->getLocation()))
1494 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001495
John McCalled976492009-12-04 22:46:56 +00001496 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1497 NewUD->setAccess(D->getAccess());
1498 Owner->addDecl(NewUD);
1499
John McCall9f54ad42009-12-10 09:41:52 +00001500 // Don't process the shadow decls for an invalid decl.
1501 if (NewUD->isInvalidDecl())
1502 return NewUD;
1503
John McCall323c3102009-12-22 22:26:37 +00001504 bool isFunctionScope = Owner->isFunctionOrMethod();
1505
John McCall9f54ad42009-12-10 09:41:52 +00001506 // Process the shadow decls.
1507 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1508 I != E; ++I) {
1509 UsingShadowDecl *Shadow = *I;
1510 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001511 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1512 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001513 TemplateArgs));
1514
1515 if (CheckRedeclaration &&
1516 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1517 continue;
1518
1519 UsingShadowDecl *InstShadow
1520 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1521 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001522
1523 if (isFunctionScope)
1524 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001525 }
John McCalled976492009-12-04 22:46:56 +00001526
1527 return NewUD;
1528}
1529
1530Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001531 // Ignore these; we handle them in bulk when processing the UsingDecl.
1532 return 0;
John McCalled976492009-12-04 22:46:56 +00001533}
1534
John McCall7ba107a2009-11-18 02:36:19 +00001535Decl * TemplateDeclInstantiator
1536 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001537 NestedNameSpecifier *NNS =
1538 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1539 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001540 TemplateArgs);
1541 if (!NNS)
1542 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001544 CXXScopeSpec SS;
1545 SS.setRange(D->getTargetNestedNameRange());
1546 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
1548 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001549 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001550 D->getUsingLoc(), SS, D->getLocation(),
1551 D->getDeclName(), 0,
1552 /*instantiation*/ true,
1553 /*typename*/ true, D->getTypenameLoc());
1554 if (UD)
John McCalled976492009-12-04 22:46:56 +00001555 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1556
John McCall7ba107a2009-11-18 02:36:19 +00001557 return UD;
1558}
1559
1560Decl * TemplateDeclInstantiator
1561 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1562 NestedNameSpecifier *NNS =
1563 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1564 D->getTargetNestedNameRange(),
1565 TemplateArgs);
1566 if (!NNS)
1567 return 0;
1568
1569 CXXScopeSpec SS;
1570 SS.setRange(D->getTargetNestedNameRange());
1571 SS.setScopeRep(NNS);
1572
1573 NamedDecl *UD =
1574 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1575 D->getUsingLoc(), SS, D->getLocation(),
1576 D->getDeclName(), 0,
1577 /*instantiation*/ true,
1578 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001579 if (UD)
John McCalled976492009-12-04 22:46:56 +00001580 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1581
Anders Carlsson0d8df782009-08-29 19:37:28 +00001582 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001583}
1584
John McCallce3ff2b2009-08-25 22:02:44 +00001585Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001586 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001587 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001588 if (D->isInvalidDecl())
1589 return 0;
1590
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001591 return Instantiator.Visit(D);
1592}
1593
John McCalle29ba202009-08-20 01:44:21 +00001594/// \brief Instantiates a nested template parameter list in the current
1595/// instantiation context.
1596///
1597/// \param L The parameter list to instantiate
1598///
1599/// \returns NULL if there was an error
1600TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001601TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001602 // Get errors for all the parameters before bailing out.
1603 bool Invalid = false;
1604
1605 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001606 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001607 ParamVector Params;
1608 Params.reserve(N);
1609 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1610 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001611 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001612 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001613 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001614 }
1615
1616 // Clean up if we had an error.
1617 if (Invalid) {
1618 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1619 PI != PE; ++PI)
1620 if (*PI)
1621 (*PI)->Destroy(SemaRef.Context);
1622 return NULL;
1623 }
1624
1625 TemplateParameterList *InstL
1626 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1627 L->getLAngleLoc(), &Params.front(), N,
1628 L->getRAngleLoc());
1629 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001630}
John McCalle29ba202009-08-20 01:44:21 +00001631
Douglas Gregored9c0f92009-10-29 00:04:11 +00001632/// \brief Instantiate the declaration of a class template partial
1633/// specialization.
1634///
1635/// \param ClassTemplate the (instantiated) class template that is partially
1636// specialized by the instantiation of \p PartialSpec.
1637///
1638/// \param PartialSpec the (uninstantiated) class template partial
1639/// specialization that we are instantiating.
1640///
1641/// \returns true if there was an error, false otherwise.
1642bool
1643TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1644 ClassTemplateDecl *ClassTemplate,
1645 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001646 // Create a local instantiation scope for this class template partial
1647 // specialization, which will contain the instantiations of the template
1648 // parameters.
1649 Sema::LocalInstantiationScope Scope(SemaRef);
1650
Douglas Gregored9c0f92009-10-29 00:04:11 +00001651 // Substitute into the template parameters of the class template partial
1652 // specialization.
1653 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1654 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1655 if (!InstParams)
1656 return true;
1657
1658 // Substitute into the template arguments of the class template partial
1659 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001660 const TemplateArgumentLoc *PartialSpecTemplateArgs
1661 = PartialSpec->getTemplateArgsAsWritten();
1662 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1663
John McCalld5532b62009-11-23 01:53:49 +00001664 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001665 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001666 TemplateArgumentLoc Loc;
1667 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001668 return true;
John McCalld5532b62009-11-23 01:53:49 +00001669 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001670 }
1671
1672
1673 // Check that the template argument list is well-formed for this
1674 // class template.
1675 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1676 InstTemplateArgs.size());
1677 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1678 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001679 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001680 false,
1681 Converted))
1682 return true;
1683
1684 // Figure out where to insert this class template partial specialization
1685 // in the member template's set of class template partial specializations.
1686 llvm::FoldingSetNodeID ID;
1687 ClassTemplatePartialSpecializationDecl::Profile(ID,
1688 Converted.getFlatArguments(),
1689 Converted.flatSize(),
1690 SemaRef.Context);
1691 void *InsertPos = 0;
1692 ClassTemplateSpecializationDecl *PrevDecl
1693 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1694 InsertPos);
1695
1696 // Build the canonical type that describes the converted template
1697 // arguments of the class template partial specialization.
1698 QualType CanonType
1699 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1700 Converted.getFlatArguments(),
1701 Converted.flatSize());
1702
1703 // Build the fully-sugared type for this class template
1704 // specialization as the user wrote in the specialization
1705 // itself. This means that we'll pretty-print the type retrieved
1706 // from the specialization's declaration the way that the user
1707 // actually wrote the specialization, rather than formatting the
1708 // name based on the "canonical" representation used to store the
1709 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001710 TypeSourceInfo *WrittenTy
1711 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1712 TemplateName(ClassTemplate),
1713 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001714 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001715 CanonType);
1716
1717 if (PrevDecl) {
1718 // We've already seen a partial specialization with the same template
1719 // parameters and template arguments. This can happen, for example, when
1720 // substituting the outer template arguments ends up causing two
1721 // class template partial specializations of a member class template
1722 // to have identical forms, e.g.,
1723 //
1724 // template<typename T, typename U>
1725 // struct Outer {
1726 // template<typename X, typename Y> struct Inner;
1727 // template<typename Y> struct Inner<T, Y>;
1728 // template<typename Y> struct Inner<U, Y>;
1729 // };
1730 //
1731 // Outer<int, int> outer; // error: the partial specializations of Inner
1732 // // have the same signature.
1733 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1734 << WrittenTy;
1735 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1736 << SemaRef.Context.getTypeDeclType(PrevDecl);
1737 return true;
1738 }
1739
1740
1741 // Create the class template partial specialization declaration.
1742 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1743 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1744 PartialSpec->getLocation(),
1745 InstParams,
1746 ClassTemplate,
1747 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001748 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001749 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001750 0,
1751 ClassTemplate->getPartialSpecializations().size());
John McCallb6217662010-03-15 10:12:16 +00001752 // Substitute the nested name specifier, if any.
1753 if (SubstQualifier(PartialSpec, InstPartialSpec))
1754 return 0;
1755
Douglas Gregored9c0f92009-10-29 00:04:11 +00001756 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1757 InstPartialSpec->setTypeAsWritten(WrittenTy);
1758
1759 // Add this partial specialization to the set of class template partial
1760 // specializations.
1761 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1762 InsertPos);
1763 return false;
1764}
1765
John McCall21ef0fa2010-03-11 09:03:00 +00001766TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001767TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001768 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001769 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1770 assert(OldTInfo && "substituting function without type source info");
1771 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001772 TypeSourceInfo *NewTInfo
1773 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1774 D->getTypeSpecStartLoc(),
1775 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001776 if (!NewTInfo)
1777 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001778
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001779 if (NewTInfo != OldTInfo) {
1780 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001781 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001782 if (FunctionProtoTypeLoc *OldProtoLoc
1783 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1784 TypeLoc NewTL = NewTInfo->getTypeLoc();
1785 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1786 assert(NewProtoLoc && "Missing prototype?");
1787 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1788 // FIXME: Variadic templates will break this.
1789 Params.push_back(NewProtoLoc->getArg(i));
1790 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001791 OldProtoLoc->getArg(i),
1792 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001793 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001794 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001795 } else {
1796 // The function type itself was not dependent and therefore no
1797 // substitution occurred. However, we still need to instantiate
1798 // the function parameters themselves.
1799 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001800 if (FunctionProtoTypeLoc *OldProtoLoc
1801 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1802 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1803 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1804 if (!Parm)
1805 return 0;
1806 Params.push_back(Parm);
1807 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001808 }
1809 }
John McCall21ef0fa2010-03-11 09:03:00 +00001810 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001811}
1812
Mike Stump1eb44332009-09-09 15:08:12 +00001813/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001814/// declaration (New) from the corresponding fields of its template (Tmpl).
1815///
1816/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001817bool
1818TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001819 FunctionDecl *Tmpl) {
1820 if (Tmpl->isDeleted())
1821 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregorcca9e962009-07-01 22:01:06 +00001823 // If we are performing substituting explicitly-specified template arguments
1824 // or deduced template arguments into a function template and we reach this
1825 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001826 // to keeping the new function template specialization. We therefore
1827 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001828 // into a template instantiation for this specific function template
1829 // specialization, which is not a SFINAE context, so that we diagnose any
1830 // further errors in the declaration itself.
1831 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1832 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1833 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1834 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001835 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001836 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001837 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001838 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001839 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001840 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1841 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001842 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001843 }
1844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001846 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1847 assert(Proto && "Function template without prototype?");
1848
1849 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1850 Proto->getNoReturnAttr()) {
1851 // The function has an exception specification or a "noreturn"
1852 // attribute. Substitute into each of the exception types.
1853 llvm::SmallVector<QualType, 4> Exceptions;
1854 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1855 // FIXME: Poor location information!
1856 QualType T
1857 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1858 New->getLocation(), New->getDeclName());
1859 if (T.isNull() ||
1860 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1861 continue;
1862
1863 Exceptions.push_back(T);
1864 }
1865
1866 // Rebuild the function type
1867
1868 const FunctionProtoType *NewProto
1869 = New->getType()->getAs<FunctionProtoType>();
1870 assert(NewProto && "Template instantiation without function prototype?");
1871 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1872 NewProto->arg_type_begin(),
1873 NewProto->getNumArgs(),
1874 NewProto->isVariadic(),
1875 NewProto->getTypeQuals(),
1876 Proto->hasExceptionSpec(),
1877 Proto->hasAnyExceptionSpec(),
1878 Exceptions.size(),
1879 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001880 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001881 }
1882
Douglas Gregore53060f2009-06-25 22:08:12 +00001883 return false;
1884}
1885
Douglas Gregor5545e162009-03-24 00:38:23 +00001886/// \brief Initializes common fields of an instantiated method
1887/// declaration (New) from the corresponding fields of its template
1888/// (Tmpl).
1889///
1890/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001891bool
1892TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001893 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001894 if (InitFunctionInstantiation(New, Tmpl))
1895 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregor5545e162009-03-24 00:38:23 +00001897 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1898 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001899 if (Tmpl->isVirtualAsWritten())
1900 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001901
1902 // FIXME: attributes
1903 // FIXME: New needs a pointer to Tmpl
1904 return false;
1905}
Douglas Gregora58861f2009-05-13 20:28:22 +00001906
1907/// \brief Instantiate the definition of the given function from its
1908/// template.
1909///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001910/// \param PointOfInstantiation the point at which the instantiation was
1911/// required. Note that this is not precisely a "point of instantiation"
1912/// for the function, but it's close.
1913///
Douglas Gregora58861f2009-05-13 20:28:22 +00001914/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001915/// function template specialization or member function of a class template
1916/// specialization.
1917///
1918/// \param Recursive if true, recursively instantiates any functions that
1919/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001920///
1921/// \param DefinitionRequired if true, then we are performing an explicit
1922/// instantiation where the body of the function is required. Complain if
1923/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001924void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001925 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001926 bool Recursive,
1927 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001928 if (Function->isInvalidDecl())
1929 return;
1930
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001931 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001933 // Never instantiate an explicit specialization.
1934 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1935 return;
1936
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001937 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001938 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001939 Stmt *Pattern = 0;
1940 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001941 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001942
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001943 if (!Pattern) {
1944 if (DefinitionRequired) {
1945 if (Function->getPrimaryTemplate())
1946 Diag(PointOfInstantiation,
1947 diag::err_explicit_instantiation_undefined_func_template)
1948 << Function->getPrimaryTemplate();
1949 else
1950 Diag(PointOfInstantiation,
1951 diag::err_explicit_instantiation_undefined_member)
1952 << 1 << Function->getDeclName() << Function->getDeclContext();
1953
1954 if (PatternDecl)
1955 Diag(PatternDecl->getLocation(),
1956 diag::note_explicit_instantiation_here);
1957 }
1958
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001959 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001960 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001961
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001962 // C++0x [temp.explicit]p9:
1963 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001964 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001965 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001966 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001967 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001968 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001969 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001971 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1972 if (Inst)
1973 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001974
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001975 // If we're performing recursive template instantiation, create our own
1976 // queue of pending implicit instantiations that we will instantiate later,
1977 // while we're still within our own instantiation context.
1978 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1979 if (Recursive)
1980 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001982 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1983
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001984 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001985 // recorded, unless we're actually a member function within a local
1986 // class, in which case we need to merge our results with the parent
1987 // scope (of the enclosing function).
1988 bool MergeWithParentScope = false;
1989 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1990 MergeWithParentScope = Rec->isLocalClass();
1991
1992 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001994 // Introduce the instantiated function parameters into the local
1995 // instantiation scope.
1996 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1997 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1998 Function->getParamDecl(I));
1999
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002000 // Enter the scope of this instantiation. We don't use
2001 // PushDeclContext because we don't have a scope.
2002 DeclContext *PreviousContext = CurContext;
2003 CurContext = Function;
2004
Mike Stump1eb44332009-09-09 15:08:12 +00002005 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00002006 getTemplateInstantiationArgs(Function);
2007
2008 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002009 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002010 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2011 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2012 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002013 }
2014
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002015 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002016 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002017
Douglas Gregor52604ab2009-09-11 21:19:12 +00002018 if (Body.isInvalid())
2019 Function->setInvalidDecl();
2020
Mike Stump1eb44332009-09-09 15:08:12 +00002021 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002022 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002023
John McCall0c01d182010-03-24 05:22:00 +00002024 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2025
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002026 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002027
2028 DeclGroupRef DG(Function);
2029 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Douglas Gregor60406be2010-01-16 22:29:39 +00002031 // This class may have local implicit instantiations that need to be
2032 // instantiation within this scope.
2033 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2034 Scope.Exit();
2035
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002036 if (Recursive) {
2037 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002038 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002039 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002041 // Restore the set of pending implicit instantiations.
2042 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2043 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002044}
2045
2046/// \brief Instantiate the definition of the given variable from its
2047/// template.
2048///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002049/// \param PointOfInstantiation the point at which the instantiation was
2050/// required. Note that this is not precisely a "point of instantiation"
2051/// for the function, but it's close.
2052///
2053/// \param Var the already-instantiated declaration of a static member
2054/// variable of a class template specialization.
2055///
2056/// \param Recursive if true, recursively instantiates any functions that
2057/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002058///
2059/// \param DefinitionRequired if true, then we are performing an explicit
2060/// instantiation where an out-of-line definition of the member variable
2061/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002062void Sema::InstantiateStaticDataMemberDefinition(
2063 SourceLocation PointOfInstantiation,
2064 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002065 bool Recursive,
2066 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002067 if (Var->isInvalidDecl())
2068 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Douglas Gregor7caa6822009-07-24 20:34:43 +00002070 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002071 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002072 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002073 assert(Def->isStaticDataMember() && "Not a static data member?");
2074 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Douglas Gregor0d035142009-10-27 18:42:08 +00002076 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002077 // We did not find an out-of-line definition of this static data member,
2078 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002079 // instantiate this definition (or provide a specialization for it) in
2080 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002081 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002082 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002083 Diag(PointOfInstantiation,
2084 diag::err_explicit_instantiation_undefined_member)
2085 << 2 << Var->getDeclName() << Var->getDeclContext();
2086 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2087 }
2088
Douglas Gregor7caa6822009-07-24 20:34:43 +00002089 return;
2090 }
2091
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002092 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002093 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002094 return;
2095
2096 // C++0x [temp.explicit]p9:
2097 // Except for inline functions, other explicit instantiation declarations
2098 // have the effect of suppressing the implicit instantiation of the entity
2099 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002100 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002101 == TSK_ExplicitInstantiationDeclaration)
2102 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Douglas Gregor7caa6822009-07-24 20:34:43 +00002104 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2105 if (Inst)
2106 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregor7caa6822009-07-24 20:34:43 +00002108 // If we're performing recursive template instantiation, create our own
2109 // queue of pending implicit instantiations that we will instantiate later,
2110 // while we're still within our own instantiation context.
2111 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2112 if (Recursive)
2113 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregor7caa6822009-07-24 20:34:43 +00002115 // Enter the scope of this instantiation. We don't use
2116 // PushDeclContext because we don't have a scope.
2117 DeclContext *PreviousContext = CurContext;
2118 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002120 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002121 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002122 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002123 CurContext = PreviousContext;
2124
2125 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002126 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2127 assert(MSInfo && "Missing member specialization information?");
2128 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2129 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002130 DeclGroupRef DG(Var);
2131 Consumer.HandleTopLevelDecl(DG);
2132 }
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregor7caa6822009-07-24 20:34:43 +00002134 if (Recursive) {
2135 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002136 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002137 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Douglas Gregor7caa6822009-07-24 20:34:43 +00002139 // Restore the set of pending implicit instantiations.
2140 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002141 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002142}
Douglas Gregor815215d2009-05-27 05:35:12 +00002143
Anders Carlsson09025312009-08-29 05:16:22 +00002144void
2145Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2146 const CXXConstructorDecl *Tmpl,
2147 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Anders Carlsson09025312009-08-29 05:16:22 +00002149 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002150 bool AnyErrors = false;
2151
Anders Carlsson09025312009-08-29 05:16:22 +00002152 // Instantiate all the initializers.
2153 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002154 InitsEnd = Tmpl->init_end();
2155 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002156 CXXBaseOrMemberInitializer *Init = *Inits;
2157
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002158 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002159 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002160 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002162 // Instantiate the initializer.
2163 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2164 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2165 AnyErrors = true;
2166 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002167 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002168
Anders Carlsson09025312009-08-29 05:16:22 +00002169 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002170 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002171 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002172 TemplateArgs,
2173 Init->getSourceLocation(),
2174 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002175 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002176 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002177 New->setInvalidDecl();
2178 continue;
2179 }
2180
John McCalla93c9342009-12-07 02:54:59 +00002181 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002182 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002183 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002184 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002185 Init->getRParenLoc(),
2186 New->getParent());
2187 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002188 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002190 // Is this an anonymous union?
2191 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002192 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2193 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002194 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002195 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2196 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002197 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002198
2199 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002200 NewArgs.size(),
2201 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002202 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002203 Init->getRParenLoc());
2204 }
2205
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002206 if (NewInit.isInvalid()) {
2207 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002208 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002209 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002210 // FIXME: It would be nice if ASTOwningVector had a release function.
2211 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Anders Carlsson09025312009-08-29 05:16:22 +00002213 NewInits.push_back((MemInitTy *)NewInit.get());
2214 }
2215 }
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Anders Carlsson09025312009-08-29 05:16:22 +00002217 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002218 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002219 /*FIXME: ColonLoc */
2220 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002221 NewInits.data(), NewInits.size(),
2222 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002223}
2224
John McCall52a575a2009-08-29 08:11:13 +00002225// TODO: this could be templated if the various decl types used the
2226// same method name.
2227static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2228 ClassTemplateDecl *Instance) {
2229 Pattern = Pattern->getCanonicalDecl();
2230
2231 do {
2232 Instance = Instance->getCanonicalDecl();
2233 if (Pattern == Instance) return true;
2234 Instance = Instance->getInstantiatedFromMemberTemplate();
2235 } while (Instance);
2236
2237 return false;
2238}
2239
Douglas Gregor0d696532009-09-28 06:34:35 +00002240static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2241 FunctionTemplateDecl *Instance) {
2242 Pattern = Pattern->getCanonicalDecl();
2243
2244 do {
2245 Instance = Instance->getCanonicalDecl();
2246 if (Pattern == Instance) return true;
2247 Instance = Instance->getInstantiatedFromMemberTemplate();
2248 } while (Instance);
2249
2250 return false;
2251}
2252
Douglas Gregored9c0f92009-10-29 00:04:11 +00002253static bool
2254isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2255 ClassTemplatePartialSpecializationDecl *Instance) {
2256 Pattern
2257 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2258 do {
2259 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2260 Instance->getCanonicalDecl());
2261 if (Pattern == Instance)
2262 return true;
2263 Instance = Instance->getInstantiatedFromMember();
2264 } while (Instance);
2265
2266 return false;
2267}
2268
John McCall52a575a2009-08-29 08:11:13 +00002269static bool isInstantiationOf(CXXRecordDecl *Pattern,
2270 CXXRecordDecl *Instance) {
2271 Pattern = Pattern->getCanonicalDecl();
2272
2273 do {
2274 Instance = Instance->getCanonicalDecl();
2275 if (Pattern == Instance) return true;
2276 Instance = Instance->getInstantiatedFromMemberClass();
2277 } while (Instance);
2278
2279 return false;
2280}
2281
2282static bool isInstantiationOf(FunctionDecl *Pattern,
2283 FunctionDecl *Instance) {
2284 Pattern = Pattern->getCanonicalDecl();
2285
2286 do {
2287 Instance = Instance->getCanonicalDecl();
2288 if (Pattern == Instance) return true;
2289 Instance = Instance->getInstantiatedFromMemberFunction();
2290 } while (Instance);
2291
2292 return false;
2293}
2294
2295static bool isInstantiationOf(EnumDecl *Pattern,
2296 EnumDecl *Instance) {
2297 Pattern = Pattern->getCanonicalDecl();
2298
2299 do {
2300 Instance = Instance->getCanonicalDecl();
2301 if (Pattern == Instance) return true;
2302 Instance = Instance->getInstantiatedFromMemberEnum();
2303 } while (Instance);
2304
2305 return false;
2306}
2307
John McCalled976492009-12-04 22:46:56 +00002308static bool isInstantiationOf(UsingShadowDecl *Pattern,
2309 UsingShadowDecl *Instance,
2310 ASTContext &C) {
2311 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2312}
2313
2314static bool isInstantiationOf(UsingDecl *Pattern,
2315 UsingDecl *Instance,
2316 ASTContext &C) {
2317 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2318}
2319
John McCall7ba107a2009-11-18 02:36:19 +00002320static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2321 UsingDecl *Instance,
2322 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002323 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002324}
2325
2326static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002327 UsingDecl *Instance,
2328 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002329 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002330}
2331
John McCall52a575a2009-08-29 08:11:13 +00002332static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2333 VarDecl *Instance) {
2334 assert(Instance->isStaticDataMember());
2335
2336 Pattern = Pattern->getCanonicalDecl();
2337
2338 do {
2339 Instance = Instance->getCanonicalDecl();
2340 if (Pattern == Instance) return true;
2341 Instance = Instance->getInstantiatedFromStaticDataMember();
2342 } while (Instance);
2343
2344 return false;
2345}
2346
John McCalled976492009-12-04 22:46:56 +00002347// Other is the prospective instantiation
2348// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002349static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002350 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002351 if (UnresolvedUsingTypenameDecl *UUD
2352 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2353 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2354 return isInstantiationOf(UUD, UD, Ctx);
2355 }
2356 }
2357
2358 if (UnresolvedUsingValueDecl *UUD
2359 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002360 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2361 return isInstantiationOf(UUD, UD, Ctx);
2362 }
2363 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002364
Anders Carlsson0d8df782009-08-29 19:37:28 +00002365 return false;
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
John McCall52a575a2009-08-29 08:11:13 +00002368 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2369 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002370
John McCall52a575a2009-08-29 08:11:13 +00002371 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2372 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002373
John McCall52a575a2009-08-29 08:11:13 +00002374 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2375 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002376
Douglas Gregor7caa6822009-07-24 20:34:43 +00002377 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002378 if (Var->isStaticDataMember())
2379 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2380
2381 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2382 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002383
Douglas Gregor0d696532009-09-28 06:34:35 +00002384 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2385 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2386
Douglas Gregored9c0f92009-10-29 00:04:11 +00002387 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2388 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2389 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2390 PartialSpec);
2391
Anders Carlssond8b285f2009-09-01 04:26:58 +00002392 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2393 if (!Field->getDeclName()) {
2394 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002395 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002396 cast<FieldDecl>(D);
2397 }
2398 }
Mike Stump1eb44332009-09-09 15:08:12 +00002399
John McCalled976492009-12-04 22:46:56 +00002400 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2401 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2402
2403 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2404 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2405
Douglas Gregor815215d2009-05-27 05:35:12 +00002406 return D->getDeclName() && isa<NamedDecl>(Other) &&
2407 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2408}
2409
2410template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002411static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002412 NamedDecl *D,
2413 ForwardIterator first,
2414 ForwardIterator last) {
2415 for (; first != last; ++first)
2416 if (isInstantiationOf(Ctx, D, *first))
2417 return cast<NamedDecl>(*first);
2418
2419 return 0;
2420}
2421
John McCall02cace72009-08-28 07:59:38 +00002422/// \brief Finds the instantiation of the given declaration context
2423/// within the current instantiation.
2424///
2425/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002426DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002427 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002428 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002429 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002430 return cast_or_null<DeclContext>(ID);
2431 } else return DC;
2432}
2433
Douglas Gregored961e72009-05-27 17:54:46 +00002434/// \brief Find the instantiation of the given declaration within the
2435/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002436///
2437/// This routine is intended to be used when \p D is a declaration
2438/// referenced from within a template, that needs to mapped into the
2439/// corresponding declaration within an instantiation. For example,
2440/// given:
2441///
2442/// \code
2443/// template<typename T>
2444/// struct X {
2445/// enum Kind {
2446/// KnownValue = sizeof(T)
2447/// };
2448///
2449/// bool getKind() const { return KnownValue; }
2450/// };
2451///
2452/// template struct X<int>;
2453/// \endcode
2454///
2455/// In the instantiation of X<int>::getKind(), we need to map the
2456/// EnumConstantDecl for KnownValue (which refers to
2457/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002458/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2459/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002460NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002461 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002462 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002463 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002464 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002465 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002466 // D is a local of some kind. Look into the map of local
2467 // declarations to their instantiations.
2468 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2469 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002470
Douglas Gregore95b4092009-09-16 18:34:49 +00002471 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2472 if (!Record->isDependentContext())
2473 return D;
2474
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002475 // If the RecordDecl is actually the injected-class-name or a
2476 // "templated" declaration for a class template, class template
2477 // partial specialization, or a member class of a class template,
2478 // substitute into the injected-class-name of the class template
2479 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002480 QualType T;
2481 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2482
2483 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002484 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002485 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2486 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002487 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002488
2489 // If we call SubstType with an InjectedClassNameType here we
2490 // can end up in an infinite loop.
2491 T = Context.getTypeDeclType(Record);
2492 assert(isa<InjectedClassNameType>(T) &&
2493 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002494 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002495 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002496
2497 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002498 // Substitute into the injected-class-name to get the type
2499 // corresponding to the instantiation we want, which may also be
2500 // the current instantiation (if we're in a template
2501 // definition). This substitution should never fail, since we
2502 // know we can instantiate the injected-class-name or we
2503 // wouldn't have gotten to the injected-class-name!
2504
2505 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2506 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002507 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2508 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2509
2510 if (!T->isDependentType()) {
2511 assert(T->isRecordType() && "Instantiation must produce a record type");
2512 return T->getAs<RecordType>()->getDecl();
2513 }
2514
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002515 // We are performing "partial" template instantiation to create
2516 // the member declarations for the members of a class template
2517 // specialization. Therefore, D is actually referring to something
2518 // in the current instantiation. Look through the current
2519 // context, which contains actual instantiations, to find the
2520 // instantiation of the "current instantiation" that D refers
2521 // to.
2522 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002523 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002524 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002525 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002526 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002527 if (isInstantiationOf(ClassTemplate,
2528 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002529 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002530
2531 if (!DC->isDependentContext())
2532 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002533 }
2534
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002535 // We're performing "instantiation" of a member of the current
2536 // instantiation while we are type-checking the
2537 // definition. Compute the declaration context and return that.
2538 assert(!SawNonDependentContext &&
2539 "No dependent context while instantiating record");
2540 DeclContext *DC = computeDeclContext(T);
2541 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002542 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002543 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002544 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002545
Douglas Gregore95b4092009-09-16 18:34:49 +00002546 // Fall through to deal with other dependent record types (e.g.,
2547 // anonymous unions in class templates).
2548 }
John McCall52a575a2009-08-29 08:11:13 +00002549
Douglas Gregore95b4092009-09-16 18:34:49 +00002550 if (!ParentDC->isDependentContext())
2551 return D;
2552
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002553 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002554 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002555 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Douglas Gregor815215d2009-05-27 05:35:12 +00002557 if (ParentDC != D->getDeclContext()) {
2558 // We performed some kind of instantiation in the parent context,
2559 // so now we need to look into the instantiated parent context to
2560 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002561
John McCall3cb0ebd2010-03-10 03:28:59 +00002562 // If our context used to be dependent, we may need to instantiate
2563 // it before performing lookup into that context.
2564 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002565 if (!Spec->isDependentContext()) {
2566 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002567 const RecordType *Tag = T->getAs<RecordType>();
2568 assert(Tag && "type of non-dependent record is not a RecordType");
2569 if (!Tag->isBeingDefined() &&
2570 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2571 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002572 }
2573 }
2574
Douglas Gregor815215d2009-05-27 05:35:12 +00002575 NamedDecl *Result = 0;
2576 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002577 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002578 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2579 } else {
2580 // Since we don't have a name for the entity we're looking for,
2581 // our only option is to walk through all of the declarations to
2582 // find that name. This will occur in a few cases:
2583 //
2584 // - anonymous struct/union within a template
2585 // - unnamed class/struct/union/enum within a template
2586 //
2587 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002588 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002589 ParentDC->decls_begin(),
2590 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002591 }
Mike Stump1eb44332009-09-09 15:08:12 +00002592
John McCall9f54ad42009-12-10 09:41:52 +00002593 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002594 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2595 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002596 && "Unable to find instantiation of declaration!");
2597
Douglas Gregor815215d2009-05-27 05:35:12 +00002598 D = Result;
2599 }
2600
Douglas Gregor815215d2009-05-27 05:35:12 +00002601 return D;
2602}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002603
Mike Stump1eb44332009-09-09 15:08:12 +00002604/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002605/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002606void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2607 while (!PendingLocalImplicitInstantiations.empty() ||
2608 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2609 PendingImplicitInstantiation Inst;
2610
2611 if (PendingLocalImplicitInstantiations.empty()) {
2612 Inst = PendingImplicitInstantiations.front();
2613 PendingImplicitInstantiations.pop_front();
2614 } else {
2615 Inst = PendingLocalImplicitInstantiations.front();
2616 PendingLocalImplicitInstantiations.pop_front();
2617 }
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor7caa6822009-07-24 20:34:43 +00002619 // Instantiate function definitions
2620 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002621 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002622 Function->getLocation(), *this,
2623 Context.getSourceManager(),
2624 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002626 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002627 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002628 continue;
2629 }
Mike Stump1eb44332009-09-09 15:08:12 +00002630
Douglas Gregor7caa6822009-07-24 20:34:43 +00002631 // Instantiate static data member definitions.
2632 VarDecl *Var = cast<VarDecl>(Inst.first);
2633 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002634
Chandler Carruth291b4412010-02-13 10:17:50 +00002635 // Don't try to instantiate declarations if the most recent redeclaration
2636 // is invalid.
2637 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2638 continue;
2639
2640 // Check if the most recent declaration has changed the specialization kind
2641 // and removed the need for implicit instantiation.
2642 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2643 case TSK_Undeclared:
2644 assert(false && "Cannot instantitiate an undeclared specialization.");
2645 case TSK_ExplicitInstantiationDeclaration:
2646 case TSK_ExplicitInstantiationDefinition:
2647 case TSK_ExplicitSpecialization:
2648 continue; // No longer need implicit instantiation.
2649 case TSK_ImplicitInstantiation:
2650 break;
2651 }
2652
Mike Stump1eb44332009-09-09 15:08:12 +00002653 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002654 Var->getLocation(), *this,
2655 Context.getSourceManager(),
2656 "instantiating static data member "
2657 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Douglas Gregor7caa6822009-07-24 20:34:43 +00002659 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002660 }
2661}
John McCall0c01d182010-03-24 05:22:00 +00002662
2663void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2664 const MultiLevelTemplateArgumentList &TemplateArgs) {
2665 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2666 E = Pattern->ddiag_end(); I != E; ++I) {
2667 DependentDiagnostic *DD = *I;
2668
2669 switch (DD->getKind()) {
2670 case DependentDiagnostic::Access:
2671 HandleDependentAccessCheck(*DD, TemplateArgs);
2672 break;
2673 }
2674 }
2675}