blob: d14ea1a9ff9fdf218b81a7a3dac18c5a384e15f5 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
Douglas Gregord57a38e2010-04-23 16:25:07 +0000203 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
204 TagDecl *TD = TT->getDecl();
205
206 // If the TagDecl that the TypedefDecl points to is an anonymous decl
207 // keep track of the TypedefDecl.
208 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
209 TD->setTypedefForAnonDecl(Typedef);
210 }
211
John McCall5126fd02009-12-30 00:31:22 +0000212 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000213 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
214 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000215 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
216 }
217
Douglas Gregord57a38e2010-04-23 16:25:07 +0000218
John McCall46460a62010-01-20 21:53:11 +0000219 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000220 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 return Typedef;
223}
224
Douglas Gregor6eef5192009-12-14 19:27:10 +0000225/// \brief Instantiate the arguments provided as part of initialization.
226///
227/// \returns true if an error occurred, false otherwise.
228static bool InstantiateInitializationArguments(Sema &SemaRef,
229 Expr **Args, unsigned NumArgs,
230 const MultiLevelTemplateArgumentList &TemplateArgs,
231 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
232 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
233 for (unsigned I = 0; I != NumArgs; ++I) {
234 // When we hit the first defaulted argument, break out of the loop:
235 // we don't pass those default arguments on.
236 if (Args[I]->isDefaultArgument())
237 break;
238
239 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
240 if (Arg.isInvalid())
241 return true;
242
243 Expr *ArgExpr = (Expr *)Arg.get();
244 InitArgs.push_back(Arg.release());
245
246 // FIXME: We're faking all of the comma locations. Do we need them?
247 FakeCommaLocs.push_back(
248 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
249 }
250
251 return false;
252}
253
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000254/// \brief Instantiate an initializer, breaking it into separate
255/// initialization arguments.
256///
257/// \param S The semantic analysis object.
258///
259/// \param Init The initializer to instantiate.
260///
261/// \param TemplateArgs Template arguments to be substituted into the
262/// initializer.
263///
264/// \param NewArgs Will be filled in with the instantiation arguments.
265///
266/// \returns true if an error occurred, false otherwise
267static bool InstantiateInitializer(Sema &S, Expr *Init,
268 const MultiLevelTemplateArgumentList &TemplateArgs,
269 SourceLocation &LParenLoc,
270 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
271 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
272 SourceLocation &RParenLoc) {
273 NewArgs.clear();
274 LParenLoc = SourceLocation();
275 RParenLoc = SourceLocation();
276
277 if (!Init)
278 return false;
279
280 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
281 Init = ExprTemp->getSubExpr();
282
283 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
284 Init = Binder->getSubExpr();
285
286 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
287 Init = ICE->getSubExprAsWritten();
288
289 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
290 LParenLoc = ParenList->getLParenLoc();
291 RParenLoc = ParenList->getRParenLoc();
292 return InstantiateInitializationArguments(S, ParenList->getExprs(),
293 ParenList->getNumExprs(),
294 TemplateArgs, CommaLocs,
295 NewArgs);
296 }
297
298 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000299 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
300 if (InstantiateInitializationArguments(S,
301 Construct->getArgs(),
302 Construct->getNumArgs(),
303 TemplateArgs,
304 CommaLocs, NewArgs))
305 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000306
Douglas Gregor28329e52010-03-24 21:22:47 +0000307 // FIXME: Fake locations!
308 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
309 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
310 return false;
311 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000312 }
313
314 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
315 if (Result.isInvalid())
316 return true;
317
318 NewArgs.push_back(Result.takeAs<Expr>());
319 return false;
320}
321
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000323 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000324 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000325 TemplateArgs,
326 D->getTypeSpecStartLoc(),
327 D->getDeclName());
328 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000329 return 0;
330
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000331 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000332 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
333 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000334 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000335 D->getStorageClass(),
336 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000337 Var->setThreadSpecified(D->isThreadSpecified());
338 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
339 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCallb6217662010-03-15 10:12:16 +0000341 // Substitute the nested name specifier, if any.
342 if (SubstQualifier(D, Var))
343 return 0;
344
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000346 // out-of-line, the instantiation will have the same lexical
347 // context (which will be a namespace scope) as the template.
348 if (D->isOutOfLine())
349 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000350
John McCall46460a62010-01-20 21:53:11 +0000351 Var->setAccess(D->getAccess());
352
Mike Stump390b4cc2009-05-16 07:39:55 +0000353 // FIXME: In theory, we could have a previous declaration for variables that
354 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000355 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000356 // FIXME: having to fake up a LookupResult is dumb.
357 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000358 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000359 if (D->isStaticDataMember())
360 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000361 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Douglas Gregor7caa6822009-07-24 20:34:43 +0000363 if (D->isOutOfLine()) {
364 D->getLexicalDeclContext()->addDecl(Var);
365 Owner->makeDeclVisibleInContext(Var);
366 } else {
367 Owner->addDecl(Var);
368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000370 // Link instantiations of static data members back to the template from
371 // which they were instantiated.
372 if (Var->isStaticDataMember())
373 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000374 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000375
Douglas Gregor60c93c92010-02-09 07:26:29 +0000376 if (Var->getAnyInitializer()) {
377 // We already have an initializer in the class.
378 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000379 if (Var->isStaticDataMember() && !D->isOutOfLine())
380 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
381 else
382 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
383
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000384 // Instantiate the initializer.
385 SourceLocation LParenLoc, RParenLoc;
386 llvm::SmallVector<SourceLocation, 4> CommaLocs;
387 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
388 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
389 CommaLocs, InitArgs, RParenLoc)) {
390 // Attach the initializer to the declaration.
391 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000392 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000393 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000394 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 move_arg(InitArgs),
396 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 RParenLoc);
398 } else if (InitArgs.size() == 1) {
399 Expr *Init = (Expr*)(InitArgs.take()[0]);
400 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
401 SemaRef.Owned(Init),
402 false);
403 } else {
404 assert(InitArgs.size() == 0);
405 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000406 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000407 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000408 // FIXME: Not too happy about invalidating the declaration
409 // because of a bogus initializer.
410 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000411 }
412
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000414 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
415 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000416
417 return Var;
418}
419
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
421 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000422 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000423 if (DI->getType()->isDependentType()) {
424 DI = SemaRef.SubstType(DI, TemplateArgs,
425 D->getLocation(), D->getDeclName());
426 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000427 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000428 Invalid = true;
429 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 // C++ [temp.arg.type]p3:
431 // If a declaration acquires a function type through a type
432 // dependent on a template-parameter and this causes a
433 // declaration that does not use the syntactic form of a
434 // function declarator to have function type, the program is
435 // ill-formed.
436 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000437 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 Invalid = true;
439 }
440 }
441
442 Expr *BitWidth = D->getBitWidth();
443 if (Invalid)
444 BitWidth = 0;
445 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000446 // The bit-width expression is not potentially evaluated.
447 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000449 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000450 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000451 if (InstantiatedBitWidth.isInvalid()) {
452 Invalid = true;
453 BitWidth = 0;
454 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000455 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
457
John McCall07fb6be2009-10-22 23:33:21 +0000458 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
459 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000460 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000461 D->getLocation(),
462 D->isMutable(),
463 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000464 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000465 D->getAccess(),
466 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000467 if (!Field) {
468 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000469 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000472 InstantiateAttrs(D, Field);
473
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000474 if (Invalid)
475 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000477 if (!Field->getDeclName()) {
478 // Keep track of where this decl came from.
479 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000482 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000483 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000484 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485
486 return Field;
487}
488
John McCall02cace72009-08-28 07:59:38 +0000489Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000490 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000491 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000492 if (TypeSourceInfo *Ty = D->getFriendType()) {
493 TypeSourceInfo *InstTy =
494 SemaRef.SubstType(Ty, TemplateArgs,
495 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000496 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000497 return 0;
John McCall02cace72009-08-28 07:59:38 +0000498
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
500 if (!FD)
501 return 0;
502
503 FD->setAccess(AS_public);
504 Owner->addDecl(FD);
505 return FD;
506 }
507
508 NamedDecl *ND = D->getFriendDecl();
509 assert(ND && "friend decl must be a decl or a type!");
510
John McCallaf2094e2010-04-08 09:05:18 +0000511 // All of the Visit implementations for the various potential friend
512 // declarations have to be carefully written to work for friend
513 // objects, with the most important detail being that the target
514 // decl should almost certainly not be placed in Owner.
515 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000516 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
John McCall02cace72009-08-28 07:59:38 +0000518 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000519 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
520 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000521 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000522 Owner->addDecl(FD);
523 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000524}
525
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000526Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
527 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregorac7610d2009-06-22 20:57:11 +0000529 // The expression in a static assertion is not potentially evaluated.
530 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000532 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000533 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534 if (InstantiatedAssertExpr.isInvalid())
535 return 0;
536
Douglas Gregor43d9d922009-08-08 01:41:12 +0000537 OwningExprResult Message(SemaRef, D->getMessage());
538 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 Decl *StaticAssert
540 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000541 move(InstantiatedAssertExpr),
542 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000543 return StaticAssert;
544}
545
546Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000547 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000548 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000549 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000551 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000552 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000553 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000554 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000555 Enum->startDefinition();
556
Douglas Gregor96084f12010-03-01 19:00:07 +0000557 if (D->getDeclContext()->isFunctionOrMethod())
558 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
559
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000560 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000561
562 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000563 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
564 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000565 EC != ECEnd; ++EC) {
566 // The specified value for the enumerator.
567 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000568 if (Expr *UninstValue = EC->getInitExpr()) {
569 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000570 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000571 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
John McCallce3ff2b2009-08-25 22:02:44 +0000573 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000574 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000575
576 // Drop the initial value and continue.
577 bool isInvalid = false;
578 if (Value.isInvalid()) {
579 Value = SemaRef.Owned((Expr *)0);
580 isInvalid = true;
581 }
582
Mike Stump1eb44332009-09-09 15:08:12 +0000583 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000584 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
585 EC->getLocation(), EC->getIdentifier(),
586 move(Value));
587
588 if (isInvalid) {
589 if (EnumConst)
590 EnumConst->setInvalidDecl();
591 Enum->setInvalidDecl();
592 }
593
594 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000595 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000596 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000597 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000598 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000599
600 if (D->getDeclContext()->isFunctionOrMethod()) {
601 // If the enumeration is within a function or method, record the enum
602 // constant as a local.
603 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
604 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605 }
606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000608 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000609 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000610 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
611 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000612 &Enumerators[0], Enumerators.size(),
613 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000614
615 return Enum;
616}
617
Douglas Gregor6477b692009-03-25 15:04:13 +0000618Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
619 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
620 return 0;
621}
622
Douglas Gregored9c0f92009-10-29 00:04:11 +0000623namespace {
624 class SortDeclByLocation {
625 SourceManager &SourceMgr;
626
627 public:
628 explicit SortDeclByLocation(SourceManager &SourceMgr)
629 : SourceMgr(SourceMgr) { }
630
631 bool operator()(const Decl *X, const Decl *Y) const {
632 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
633 Y->getLocation());
634 }
635 };
636}
637
John McCalle29ba202009-08-20 01:44:21 +0000638Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000639 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
640
Douglas Gregor550d9b22009-10-31 17:21:17 +0000641 // Create a local instantiation scope for this class template, which
642 // will contain the instantiations of the template parameters.
643 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000644 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000645 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000646 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000647 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000648
649 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000650
651 // Instantiate the qualifier. We have to do this first in case
652 // we're a friend declaration, because if we are then we need to put
653 // the new declaration in the appropriate context.
654 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
655 if (Qualifier) {
656 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
657 Pattern->getQualifierRange(),
658 TemplateArgs);
659 if (!Qualifier) return 0;
660 }
661
662 CXXRecordDecl *PrevDecl = 0;
663 ClassTemplateDecl *PrevClassTemplate = 0;
664
665 // If this isn't a friend, then it's a member template, in which
666 // case we just want to build the instantiation in the
667 // specialization. If it is a friend, we want to build it in
668 // the appropriate context.
669 DeclContext *DC = Owner;
670 if (isFriend) {
671 if (Qualifier) {
672 CXXScopeSpec SS;
673 SS.setScopeRep(Qualifier);
674 SS.setRange(Pattern->getQualifierRange());
675 DC = SemaRef.computeDeclContext(SS);
676 if (!DC) return 0;
677 } else {
678 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
679 Pattern->getDeclContext(),
680 TemplateArgs);
681 }
682
683 // Look for a previous declaration of the template in the owning
684 // context.
685 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
686 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
687 SemaRef.LookupQualifiedName(R, DC);
688
689 if (R.isSingleResult()) {
690 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
691 if (PrevClassTemplate)
692 PrevDecl = PrevClassTemplate->getTemplatedDecl();
693 }
694
695 if (!PrevClassTemplate && Qualifier) {
696 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000697 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
698 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000699 return 0;
700 }
701
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000702 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000703 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000704 bool Complain = true;
705
706 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
707 // template for struct std::tr1::__detail::_Map_base, where the
708 // template parameters of the friend declaration don't match the
709 // template parameters of the original declaration. In this one
710 // case, we don't complain about the ill-formed friend
711 // declaration.
712 if (isFriend && Pattern->getIdentifier() &&
713 Pattern->getIdentifier()->isStr("_Map_base") &&
714 DC->isNamespace() &&
715 cast<NamespaceDecl>(DC)->getIdentifier() &&
716 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
717 DeclContext *DCParent = DC->getParent();
718 if (DCParent->isNamespace() &&
719 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
720 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
721 DeclContext *DCParent2 = DCParent->getParent();
722 if (DCParent2->isNamespace() &&
723 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
724 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
725 DCParent2->getParent()->isTranslationUnit())
726 Complain = false;
727 }
728 }
729
John McCall93ba8572010-03-25 06:39:04 +0000730 TemplateParameterList *PrevParams
731 = PrevClassTemplate->getTemplateParameters();
732
733 // Make sure the parameter lists match.
734 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000735 Complain,
736 Sema::TPL_TemplateMatch)) {
737 if (Complain)
738 return 0;
739
740 AdoptedPreviousTemplateParams = true;
741 InstParams = PrevParams;
742 }
John McCall93ba8572010-03-25 06:39:04 +0000743
744 // Do some additional validation, then merge default arguments
745 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000746 if (!AdoptedPreviousTemplateParams &&
747 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000748 Sema::TPC_ClassTemplate))
749 return 0;
750 }
751 }
752
John McCalle29ba202009-08-20 01:44:21 +0000753 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000754 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000755 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000756 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000757 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000758
John McCall93ba8572010-03-25 06:39:04 +0000759 if (Qualifier)
760 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000761
John McCalle29ba202009-08-20 01:44:21 +0000762 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000763 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
764 D->getIdentifier(), InstParams, RecordInst,
765 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000766 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000767
John McCall93ba8572010-03-25 06:39:04 +0000768 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000769 if (PrevClassTemplate)
770 Inst->setAccess(PrevClassTemplate->getAccess());
771 else
772 Inst->setAccess(D->getAccess());
773
John McCall93ba8572010-03-25 06:39:04 +0000774 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
775 // TODO: do we want to track the instantiation progeny of this
776 // friend target decl?
777 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000779 Inst->setInstantiatedFromMemberTemplate(D);
780 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000781
782 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000783 SemaRef.Context.getInjectedClassNameType(RecordInst,
784 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000785
Douglas Gregor259571e2009-10-30 22:42:42 +0000786 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000787 if (isFriend) {
788 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000789 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000790 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000791
John McCalle29ba202009-08-20 01:44:21 +0000792 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000793
794 // First, we sort the partial specializations by location, so
795 // that we instantiate them in the order they were declared.
796 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
797 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
798 P = D->getPartialSpecializations().begin(),
799 PEnd = D->getPartialSpecializations().end();
800 P != PEnd; ++P)
801 PartialSpecs.push_back(&*P);
802 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
803 SortDeclByLocation(SemaRef.SourceMgr));
804
805 // Instantiate all of the partial specializations of this member class
806 // template.
807 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
808 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
809
John McCalle29ba202009-08-20 01:44:21 +0000810 return Inst;
811}
812
Douglas Gregord60e1052009-08-27 16:57:43 +0000813Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000814TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
815 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000816 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
817
818 // Lookup the already-instantiated declaration in the instantiation
819 // of the class template and return that.
820 DeclContext::lookup_result Found
821 = Owner->lookup(ClassTemplate->getDeclName());
822 if (Found.first == Found.second)
823 return 0;
824
825 ClassTemplateDecl *InstClassTemplate
826 = dyn_cast<ClassTemplateDecl>(*Found.first);
827 if (!InstClassTemplate)
828 return 0;
829
830 Decl *DCanon = D->getCanonicalDecl();
831 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
832 P = InstClassTemplate->getPartialSpecializations().begin(),
833 PEnd = InstClassTemplate->getPartialSpecializations().end();
834 P != PEnd; ++P) {
835 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
836 return &*P;
837 }
838
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000839 return 0;
840}
841
842Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000843TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000844 // Create a local instantiation scope for this function template, which
845 // will contain the instantiations of the template parameters and then get
846 // merged with the local instantiation scope for the function template
847 // itself.
848 Sema::LocalInstantiationScope Scope(SemaRef);
849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 TemplateParameterList *TempParams = D->getTemplateParameters();
851 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000852 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000853 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000854
Douglas Gregora735b202009-10-13 14:39:41 +0000855 FunctionDecl *Instantiated = 0;
856 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
857 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
858 InstParams));
859 else
860 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
861 D->getTemplatedDecl(),
862 InstParams));
863
864 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000865 return 0;
866
John McCall46460a62010-01-20 21:53:11 +0000867 Instantiated->setAccess(D->getAccess());
868
Mike Stump1eb44332009-09-09 15:08:12 +0000869 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000871 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000872 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000873 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000874 assert(InstTemplate &&
875 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000876
John McCallb1a56e72010-03-26 23:10:15 +0000877 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
878
John McCalle976ffe2009-12-14 23:19:40 +0000879 // Link the instantiation back to the pattern *unless* this is a
880 // non-definition friend declaration.
881 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000882 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000883 InstTemplate->setInstantiatedFromMemberTemplate(D);
884
John McCallb1a56e72010-03-26 23:10:15 +0000885 // Make declarations visible in the appropriate context.
886 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000887 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000888
Douglas Gregord60e1052009-08-27 16:57:43 +0000889 return InstTemplate;
890}
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
893 CXXRecordDecl *PrevDecl = 0;
894 if (D->isInjectedClassName())
895 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000896 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000897 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
898 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000899 TemplateArgs);
900 if (!Prev) return 0;
901 PrevDecl = cast<CXXRecordDecl>(Prev);
902 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000903
904 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000905 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000906 D->getLocation(), D->getIdentifier(),
907 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000908
909 // Substitute the nested name specifier, if any.
910 if (SubstQualifier(D, Record))
911 return 0;
912
Douglas Gregord475b8d2009-03-25 21:17:03 +0000913 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000914 // FIXME: Check against AS_none is an ugly hack to work around the issue that
915 // the tag decls introduced by friend class declarations don't have an access
916 // specifier. Remove once this area of the code gets sorted out.
917 if (D->getAccess() != AS_none)
918 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000919 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000920 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000921
John McCall02cace72009-08-28 07:59:38 +0000922 // If the original function was part of a friend declaration,
923 // inherit its namespace state.
924 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
925 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
926
Anders Carlssond8b285f2009-09-01 04:26:58 +0000927 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
928
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000929 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000930 return Record;
931}
932
John McCall02cace72009-08-28 07:59:38 +0000933/// Normal class members are of more specific types and therefore
934/// don't make it here. This function serves two purposes:
935/// 1) instantiating function templates
936/// 2) substituting friend declarations
937/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000938Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000939 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000940 // Check whether there is already a function template specialization for
941 // this declaration.
942 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
943 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000944 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000945 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000946 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000947 TemplateArgs.getInnermost().getFlatArgumentList(),
948 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000949 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
951 FunctionTemplateSpecializationInfo *Info
952 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000953 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregor127102b2009-06-29 20:59:39 +0000955 // If we already have a function template specialization, return it.
956 if (Info)
957 return Info->Function;
958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
John McCallb0cb0222010-03-27 05:57:59 +0000960 bool isFriend;
961 if (FunctionTemplate)
962 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
963 else
964 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
965
Douglas Gregor79c22782010-01-16 20:21:20 +0000966 bool MergeWithParentScope = (TemplateParams != 0) ||
967 !(isa<Decl>(Owner) &&
968 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
969 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregore53060f2009-06-25 22:08:12 +0000971 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000972 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
973 TInfo = SubstFunctionType(D, Params);
974 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000975 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000976 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000977
John McCalld325daa2010-03-26 04:53:08 +0000978 NestedNameSpecifier *Qualifier = D->getQualifier();
979 if (Qualifier) {
980 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
981 D->getQualifierRange(),
982 TemplateArgs);
983 if (!Qualifier) return 0;
984 }
985
John McCall68b6b872010-02-06 01:50:47 +0000986 // If we're instantiating a local function declaration, put the result
987 // in the owner; otherwise we need to find the instantiated context.
988 DeclContext *DC;
989 if (D->getDeclContext()->isFunctionOrMethod())
990 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000991 else if (isFriend && Qualifier) {
992 CXXScopeSpec SS;
993 SS.setScopeRep(Qualifier);
994 SS.setRange(D->getQualifierRange());
995 DC = SemaRef.computeDeclContext(SS);
996 if (!DC) return 0;
997 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000998 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
999 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001000 }
John McCall68b6b872010-02-06 01:50:47 +00001001
John McCall02cace72009-08-28 07:59:38 +00001002 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001003 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001004 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001005 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001006 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001007
John McCalld325daa2010-03-26 04:53:08 +00001008 if (Qualifier)
1009 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001010
John McCallb1a56e72010-03-26 23:10:15 +00001011 DeclContext *LexicalDC = Owner;
1012 if (!isFriend && D->isOutOfLine()) {
1013 assert(D->getDeclContext()->isFileContext());
1014 LexicalDC = D->getDeclContext();
1015 }
1016
1017 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Douglas Gregore53060f2009-06-25 22:08:12 +00001019 // Attach the parameters
1020 for (unsigned P = 0; P < Params.size(); ++P)
1021 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001022 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001023
Douglas Gregora735b202009-10-13 14:39:41 +00001024 if (TemplateParams) {
1025 // Our resulting instantiation is actually a function template, since we
1026 // are substituting only the outer template parameters. For example, given
1027 //
1028 // template<typename T>
1029 // struct X {
1030 // template<typename U> friend void f(T, U);
1031 // };
1032 //
1033 // X<int> x;
1034 //
1035 // We are instantiating the friend function template "f" within X<int>,
1036 // which means substituting int for T, but leaving "f" as a friend function
1037 // template.
1038 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001039 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001040 Function->getLocation(),
1041 Function->getDeclName(),
1042 TemplateParams, Function);
1043 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001044
1045 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001046
1047 if (isFriend && D->isThisDeclarationADefinition()) {
1048 // TODO: should we remember this connection regardless of whether
1049 // the friend declaration provided a body?
1050 FunctionTemplate->setInstantiatedFromMemberTemplate(
1051 D->getDescribedFunctionTemplate());
1052 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001053 } else if (FunctionTemplate) {
1054 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001055 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001056 &TemplateArgs.getInnermost(),
1057 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001058 } else if (isFriend && D->isThisDeclarationADefinition()) {
1059 // TODO: should we remember this connection regardless of whether
1060 // the friend declaration provided a body?
1061 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001062 }
Douglas Gregora735b202009-10-13 14:39:41 +00001063
Douglas Gregore53060f2009-06-25 22:08:12 +00001064 if (InitFunctionInstantiation(Function, D))
1065 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregore53060f2009-06-25 22:08:12 +00001067 bool Redeclaration = false;
1068 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001069 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001070
John McCall68263142009-11-18 22:49:29 +00001071 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1072 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1073
John McCallaf2094e2010-04-08 09:05:18 +00001074 if (DependentFunctionTemplateSpecializationInfo *Info
1075 = D->getDependentSpecializationInfo()) {
1076 assert(isFriend && "non-friend has dependent specialization info?");
1077
1078 // This needs to be set now for future sanity.
1079 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1080
1081 // Instantiate the explicit template arguments.
1082 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1083 Info->getRAngleLoc());
1084 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1085 TemplateArgumentLoc Loc;
1086 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1087 return 0;
1088
1089 ExplicitArgs.addArgument(Loc);
1090 }
1091
1092 // Map the candidate templates to their instantiations.
1093 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1094 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1095 Info->getTemplate(I),
1096 TemplateArgs);
1097 if (!Temp) return 0;
1098
1099 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1100 }
1101
1102 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1103 &ExplicitArgs,
1104 Previous))
1105 Function->setInvalidDecl();
1106
1107 isExplicitSpecialization = true;
1108
1109 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // Look only into the namespace where the friend would be declared to
1111 // find a previous declaration. This is the innermost enclosing namespace,
1112 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001113 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001114
Douglas Gregora735b202009-10-13 14:39:41 +00001115 // In C++, the previous declaration we find might be a tag type
1116 // (class or enum). In this case, the new declaration will hide the
1117 // tag type. Note that this does does not apply if we're declaring a
1118 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001119 if (Previous.isSingleTagDecl())
1120 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001121 }
1122
John McCall9f54ad42009-12-10 09:41:52 +00001123 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001124 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001125 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001126
John McCall76d32642010-04-24 01:30:58 +00001127 NamedDecl *PrincipalDecl = (TemplateParams
1128 ? cast<NamedDecl>(FunctionTemplate)
1129 : Function);
1130
Douglas Gregora735b202009-10-13 14:39:41 +00001131 // If the original function was part of a friend declaration,
1132 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001133 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001134 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001135 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001136 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001137 else
Douglas Gregora735b202009-10-13 14:39:41 +00001138 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001139
1140 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1141 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001142 }
1143
John McCall76d32642010-04-24 01:30:58 +00001144 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1145 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1146 PrincipalDecl->setNonMemberOperator();
1147
Douglas Gregore53060f2009-06-25 22:08:12 +00001148 return Function;
1149}
1150
Douglas Gregord60e1052009-08-27 16:57:43 +00001151Decl *
1152TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1153 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001154 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1155 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001156 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001157 // We are creating a function template specialization from a function
1158 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001159 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001160 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001161 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001162 TemplateArgs.getInnermost().getFlatArgumentList(),
1163 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001164 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
1166 FunctionTemplateSpecializationInfo *Info
1167 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001168 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Douglas Gregor6b906862009-08-21 00:16:32 +00001170 // If we already have a function template specialization, return it.
1171 if (Info)
1172 return Info->Function;
1173 }
1174
John McCallb0cb0222010-03-27 05:57:59 +00001175 bool isFriend;
1176 if (FunctionTemplate)
1177 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1178 else
1179 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1180
Douglas Gregor79c22782010-01-16 20:21:20 +00001181 bool MergeWithParentScope = (TemplateParams != 0) ||
1182 !(isa<Decl>(Owner) &&
1183 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1184 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001185
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001186 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001187 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1188 TInfo = SubstFunctionType(D, Params);
1189 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001190 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001191 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001192
John McCallb0cb0222010-03-27 05:57:59 +00001193 NestedNameSpecifier *Qualifier = D->getQualifier();
1194 if (Qualifier) {
1195 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1196 D->getQualifierRange(),
1197 TemplateArgs);
1198 if (!Qualifier) return 0;
1199 }
1200
1201 DeclContext *DC = Owner;
1202 if (isFriend) {
1203 if (Qualifier) {
1204 CXXScopeSpec SS;
1205 SS.setScopeRep(Qualifier);
1206 SS.setRange(D->getQualifierRange());
1207 DC = SemaRef.computeDeclContext(SS);
1208 } else {
1209 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1210 D->getDeclContext(),
1211 TemplateArgs);
1212 }
1213 if (!DC) return 0;
1214 }
1215
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001216 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001217 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001218 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregordec06662009-08-21 18:42:58 +00001220 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001221 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001222 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1223 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1224 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001225 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1226 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001227 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001229 Constructor->isInlineSpecified(),
1230 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001231 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1232 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1233 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1234 SemaRef.Context.getCanonicalType(ClassTy));
1235 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1236 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001237 T, Destructor->isInlineSpecified(),
1238 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001239 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001240 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001241 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001242 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001243 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1244 ConvTy);
1245 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1246 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001247 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001248 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001249 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001250 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001251 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001252 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001253 D->isStatic(),
1254 D->getStorageClassAsWritten(),
1255 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001256 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001257
John McCallb0cb0222010-03-27 05:57:59 +00001258 if (Qualifier)
1259 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001260
Douglas Gregord60e1052009-08-27 16:57:43 +00001261 if (TemplateParams) {
1262 // Our resulting instantiation is actually a function template, since we
1263 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001264 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001265 // template<typename T>
1266 // struct X {
1267 // template<typename U> void f(T, U);
1268 // };
1269 //
1270 // X<int> x;
1271 //
1272 // We are instantiating the member template "f" within X<int>, which means
1273 // substituting int for T, but leaving "f" as a member function template.
1274 // Build the function template itself.
1275 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1276 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001277 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001278 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001279 if (isFriend) {
1280 FunctionTemplate->setLexicalDeclContext(Owner);
1281 FunctionTemplate->setObjectOfFriendDecl(true);
1282 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001283 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001284 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001285 } else if (FunctionTemplate) {
1286 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001287 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001288 &TemplateArgs.getInnermost(),
1289 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001290 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001291 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001292 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001293 }
1294
Mike Stump1eb44332009-09-09 15:08:12 +00001295 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001296 // out-of-line, the instantiation will have the same lexical
1297 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001298 if (isFriend) {
1299 Method->setLexicalDeclContext(Owner);
1300 Method->setObjectOfFriendDecl(true);
1301 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001302 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregor5545e162009-03-24 00:38:23 +00001304 // Attach the parameters
1305 for (unsigned P = 0; P < Params.size(); ++P)
1306 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001307 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001308
1309 if (InitMethodInstantiation(Method, D))
1310 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001311
John McCall68263142009-11-18 22:49:29 +00001312 LookupResult Previous(SemaRef, Name, SourceLocation(),
1313 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
John McCallb0cb0222010-03-27 05:57:59 +00001315 if (!FunctionTemplate || TemplateParams || isFriend) {
1316 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregordec06662009-08-21 18:42:58 +00001318 // In C++, the previous declaration we find might be a tag type
1319 // (class or enum). In this case, the new declaration will hide the
1320 // tag type. Note that this does does not apply if we're declaring a
1321 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001322 if (Previous.isSingleTagDecl())
1323 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001324 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001325
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001326 bool Redeclaration = false;
1327 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001328 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001329 /*FIXME:*/OverloadableAttrRequired);
1330
Douglas Gregor4ba31362009-12-01 17:24:26 +00001331 if (D->isPure())
1332 SemaRef.CheckPureMethod(Method, SourceRange());
1333
John McCall46460a62010-01-20 21:53:11 +00001334 Method->setAccess(D->getAccess());
1335
John McCallb0cb0222010-03-27 05:57:59 +00001336 if (FunctionTemplate) {
1337 // If there's a function template, let our caller handle it.
1338 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1339 // Don't hide a (potentially) valid declaration with an invalid one.
1340 } else {
1341 NamedDecl *DeclToAdd = (TemplateParams
1342 ? cast<NamedDecl>(FunctionTemplate)
1343 : Method);
1344 if (isFriend)
1345 Record->makeDeclVisibleInContext(DeclToAdd);
1346 else
1347 Owner->addDecl(DeclToAdd);
1348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001350 return Method;
1351}
1352
Douglas Gregor615c5d42009-03-24 16:43:20 +00001353Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001354 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001355}
1356
Douglas Gregor03b2b072009-03-24 00:15:49 +00001357Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001358 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001359}
1360
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001361Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001362 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001363}
1364
Douglas Gregor6477b692009-03-25 15:04:13 +00001365ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001366 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001367}
1368
John McCalle29ba202009-08-20 01:44:21 +00001369Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1370 TemplateTypeParmDecl *D) {
1371 // TODO: don't always clone when decls are refcounted.
1372 const Type* T = D->getTypeForDecl();
1373 assert(T->isTemplateTypeParmType());
1374 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001375
John McCalle29ba202009-08-20 01:44:21 +00001376 TemplateTypeParmDecl *Inst =
1377 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001378 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001379 TTPT->getName(),
1380 D->wasDeclaredWithTypename(),
1381 D->isParameterPack());
1382
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001383 if (D->hasDefaultArgument())
1384 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001385
Douglas Gregor550d9b22009-10-31 17:21:17 +00001386 // Introduce this template parameter's instantiation into the instantiation
1387 // scope.
1388 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1389
John McCalle29ba202009-08-20 01:44:21 +00001390 return Inst;
1391}
1392
Douglas Gregor33642df2009-10-23 23:25:44 +00001393Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1394 NonTypeTemplateParmDecl *D) {
1395 // Substitute into the type of the non-type template parameter.
1396 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001397 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001398 if (DI) {
1399 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1400 D->getDeclName());
1401 if (DI) T = DI->getType();
1402 } else {
1403 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1404 D->getDeclName());
1405 DI = 0;
1406 }
1407 if (T.isNull())
1408 return 0;
1409
1410 // Check that this type is acceptable for a non-type template parameter.
1411 bool Invalid = false;
1412 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1413 if (T.isNull()) {
1414 T = SemaRef.Context.IntTy;
1415 Invalid = true;
1416 }
1417
1418 NonTypeTemplateParmDecl *Param
1419 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1420 D->getDepth() - 1, D->getPosition(),
1421 D->getIdentifier(), T, DI);
1422 if (Invalid)
1423 Param->setInvalidDecl();
1424
1425 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001426
1427 // Introduce this template parameter's instantiation into the instantiation
1428 // scope.
1429 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001430 return Param;
1431}
1432
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001433Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001434TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1435 TemplateTemplateParmDecl *D) {
1436 // Instantiate the template parameter list of the template template parameter.
1437 TemplateParameterList *TempParams = D->getTemplateParameters();
1438 TemplateParameterList *InstParams;
1439 {
1440 // Perform the actual substitution of template parameters within a new,
1441 // local instantiation scope.
1442 Sema::LocalInstantiationScope Scope(SemaRef);
1443 InstParams = SubstTemplateParams(TempParams);
1444 if (!InstParams)
1445 return NULL;
1446 }
1447
1448 // Build the template template parameter.
1449 TemplateTemplateParmDecl *Param
1450 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1451 D->getDepth() - 1, D->getPosition(),
1452 D->getIdentifier(), InstParams);
1453 Param->setDefaultArgument(D->getDefaultArgument());
1454
1455 // Introduce this template parameter's instantiation into the instantiation
1456 // scope.
1457 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1458
1459 return Param;
1460}
1461
Douglas Gregor48c32a72009-11-17 06:07:40 +00001462Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1463 // Using directives are never dependent, so they require no explicit
1464
1465 UsingDirectiveDecl *Inst
1466 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1467 D->getNamespaceKeyLocation(),
1468 D->getQualifierRange(), D->getQualifier(),
1469 D->getIdentLocation(),
1470 D->getNominatedNamespace(),
1471 D->getCommonAncestor());
1472 Owner->addDecl(Inst);
1473 return Inst;
1474}
1475
John McCalled976492009-12-04 22:46:56 +00001476Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1477 // The nested name specifier is non-dependent, so no transformation
1478 // is required.
1479
John McCall9f54ad42009-12-10 09:41:52 +00001480 // We only need to do redeclaration lookups if we're in a class
1481 // scope (in fact, it's not really even possible in non-class
1482 // scopes).
1483 bool CheckRedeclaration = Owner->isRecord();
1484
1485 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1486 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1487
John McCalled976492009-12-04 22:46:56 +00001488 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1489 D->getLocation(),
1490 D->getNestedNameRange(),
1491 D->getUsingLocation(),
1492 D->getTargetNestedNameDecl(),
1493 D->getDeclName(),
1494 D->isTypeName());
1495
1496 CXXScopeSpec SS;
1497 SS.setScopeRep(D->getTargetNestedNameDecl());
1498 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001499
1500 if (CheckRedeclaration) {
1501 Prev.setHideTags(false);
1502 SemaRef.LookupQualifiedName(Prev, Owner);
1503
1504 // Check for invalid redeclarations.
1505 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1506 D->isTypeName(), SS,
1507 D->getLocation(), Prev))
1508 NewUD->setInvalidDecl();
1509
1510 }
1511
1512 if (!NewUD->isInvalidDecl() &&
1513 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001514 D->getLocation()))
1515 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001516
John McCalled976492009-12-04 22:46:56 +00001517 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1518 NewUD->setAccess(D->getAccess());
1519 Owner->addDecl(NewUD);
1520
John McCall9f54ad42009-12-10 09:41:52 +00001521 // Don't process the shadow decls for an invalid decl.
1522 if (NewUD->isInvalidDecl())
1523 return NewUD;
1524
John McCall323c3102009-12-22 22:26:37 +00001525 bool isFunctionScope = Owner->isFunctionOrMethod();
1526
John McCall9f54ad42009-12-10 09:41:52 +00001527 // Process the shadow decls.
1528 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1529 I != E; ++I) {
1530 UsingShadowDecl *Shadow = *I;
1531 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001532 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1533 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001534 TemplateArgs));
1535
1536 if (CheckRedeclaration &&
1537 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1538 continue;
1539
1540 UsingShadowDecl *InstShadow
1541 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1542 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001543
1544 if (isFunctionScope)
1545 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001546 }
John McCalled976492009-12-04 22:46:56 +00001547
1548 return NewUD;
1549}
1550
1551Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001552 // Ignore these; we handle them in bulk when processing the UsingDecl.
1553 return 0;
John McCalled976492009-12-04 22:46:56 +00001554}
1555
John McCall7ba107a2009-11-18 02:36:19 +00001556Decl * TemplateDeclInstantiator
1557 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001558 NestedNameSpecifier *NNS =
1559 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1560 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001561 TemplateArgs);
1562 if (!NNS)
1563 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001565 CXXScopeSpec SS;
1566 SS.setRange(D->getTargetNestedNameRange());
1567 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
1569 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001570 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001571 D->getUsingLoc(), SS, D->getLocation(),
1572 D->getDeclName(), 0,
1573 /*instantiation*/ true,
1574 /*typename*/ true, D->getTypenameLoc());
1575 if (UD)
John McCalled976492009-12-04 22:46:56 +00001576 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1577
John McCall7ba107a2009-11-18 02:36:19 +00001578 return UD;
1579}
1580
1581Decl * TemplateDeclInstantiator
1582 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1583 NestedNameSpecifier *NNS =
1584 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1585 D->getTargetNestedNameRange(),
1586 TemplateArgs);
1587 if (!NNS)
1588 return 0;
1589
1590 CXXScopeSpec SS;
1591 SS.setRange(D->getTargetNestedNameRange());
1592 SS.setScopeRep(NNS);
1593
1594 NamedDecl *UD =
1595 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1596 D->getUsingLoc(), SS, D->getLocation(),
1597 D->getDeclName(), 0,
1598 /*instantiation*/ true,
1599 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001600 if (UD)
John McCalled976492009-12-04 22:46:56 +00001601 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1602
Anders Carlsson0d8df782009-08-29 19:37:28 +00001603 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001604}
1605
John McCallce3ff2b2009-08-25 22:02:44 +00001606Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001607 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001608 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001609 if (D->isInvalidDecl())
1610 return 0;
1611
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001612 return Instantiator.Visit(D);
1613}
1614
John McCalle29ba202009-08-20 01:44:21 +00001615/// \brief Instantiates a nested template parameter list in the current
1616/// instantiation context.
1617///
1618/// \param L The parameter list to instantiate
1619///
1620/// \returns NULL if there was an error
1621TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001622TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001623 // Get errors for all the parameters before bailing out.
1624 bool Invalid = false;
1625
1626 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001627 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001628 ParamVector Params;
1629 Params.reserve(N);
1630 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1631 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001632 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001633 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001634 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001635 }
1636
1637 // Clean up if we had an error.
1638 if (Invalid) {
1639 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1640 PI != PE; ++PI)
1641 if (*PI)
1642 (*PI)->Destroy(SemaRef.Context);
1643 return NULL;
1644 }
1645
1646 TemplateParameterList *InstL
1647 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1648 L->getLAngleLoc(), &Params.front(), N,
1649 L->getRAngleLoc());
1650 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001651}
John McCalle29ba202009-08-20 01:44:21 +00001652
Douglas Gregored9c0f92009-10-29 00:04:11 +00001653/// \brief Instantiate the declaration of a class template partial
1654/// specialization.
1655///
1656/// \param ClassTemplate the (instantiated) class template that is partially
1657// specialized by the instantiation of \p PartialSpec.
1658///
1659/// \param PartialSpec the (uninstantiated) class template partial
1660/// specialization that we are instantiating.
1661///
1662/// \returns true if there was an error, false otherwise.
1663bool
1664TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1665 ClassTemplateDecl *ClassTemplate,
1666 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001667 // Create a local instantiation scope for this class template partial
1668 // specialization, which will contain the instantiations of the template
1669 // parameters.
1670 Sema::LocalInstantiationScope Scope(SemaRef);
1671
Douglas Gregored9c0f92009-10-29 00:04:11 +00001672 // Substitute into the template parameters of the class template partial
1673 // specialization.
1674 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1675 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1676 if (!InstParams)
1677 return true;
1678
1679 // Substitute into the template arguments of the class template partial
1680 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001681 const TemplateArgumentLoc *PartialSpecTemplateArgs
1682 = PartialSpec->getTemplateArgsAsWritten();
1683 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1684
John McCalld5532b62009-11-23 01:53:49 +00001685 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001686 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001687 TemplateArgumentLoc Loc;
1688 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001689 return true;
John McCalld5532b62009-11-23 01:53:49 +00001690 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001691 }
1692
1693
1694 // Check that the template argument list is well-formed for this
1695 // class template.
1696 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1697 InstTemplateArgs.size());
1698 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1699 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001700 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001701 false,
1702 Converted))
1703 return true;
1704
1705 // Figure out where to insert this class template partial specialization
1706 // in the member template's set of class template partial specializations.
1707 llvm::FoldingSetNodeID ID;
1708 ClassTemplatePartialSpecializationDecl::Profile(ID,
1709 Converted.getFlatArguments(),
1710 Converted.flatSize(),
1711 SemaRef.Context);
1712 void *InsertPos = 0;
1713 ClassTemplateSpecializationDecl *PrevDecl
1714 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1715 InsertPos);
1716
1717 // Build the canonical type that describes the converted template
1718 // arguments of the class template partial specialization.
1719 QualType CanonType
1720 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1721 Converted.getFlatArguments(),
1722 Converted.flatSize());
1723
1724 // Build the fully-sugared type for this class template
1725 // specialization as the user wrote in the specialization
1726 // itself. This means that we'll pretty-print the type retrieved
1727 // from the specialization's declaration the way that the user
1728 // actually wrote the specialization, rather than formatting the
1729 // name based on the "canonical" representation used to store the
1730 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001731 TypeSourceInfo *WrittenTy
1732 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1733 TemplateName(ClassTemplate),
1734 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001735 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001736 CanonType);
1737
1738 if (PrevDecl) {
1739 // We've already seen a partial specialization with the same template
1740 // parameters and template arguments. This can happen, for example, when
1741 // substituting the outer template arguments ends up causing two
1742 // class template partial specializations of a member class template
1743 // to have identical forms, e.g.,
1744 //
1745 // template<typename T, typename U>
1746 // struct Outer {
1747 // template<typename X, typename Y> struct Inner;
1748 // template<typename Y> struct Inner<T, Y>;
1749 // template<typename Y> struct Inner<U, Y>;
1750 // };
1751 //
1752 // Outer<int, int> outer; // error: the partial specializations of Inner
1753 // // have the same signature.
1754 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1755 << WrittenTy;
1756 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1757 << SemaRef.Context.getTypeDeclType(PrevDecl);
1758 return true;
1759 }
1760
1761
1762 // Create the class template partial specialization declaration.
1763 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1764 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1765 PartialSpec->getLocation(),
1766 InstParams,
1767 ClassTemplate,
1768 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001769 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001770 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001771 0);
John McCallb6217662010-03-15 10:12:16 +00001772 // Substitute the nested name specifier, if any.
1773 if (SubstQualifier(PartialSpec, InstPartialSpec))
1774 return 0;
1775
Douglas Gregored9c0f92009-10-29 00:04:11 +00001776 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1777 InstPartialSpec->setTypeAsWritten(WrittenTy);
1778
1779 // Add this partial specialization to the set of class template partial
1780 // specializations.
1781 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1782 InsertPos);
1783 return false;
1784}
1785
John McCall21ef0fa2010-03-11 09:03:00 +00001786TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001787TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001788 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001789 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1790 assert(OldTInfo && "substituting function without type source info");
1791 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001792 TypeSourceInfo *NewTInfo
1793 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1794 D->getTypeSpecStartLoc(),
1795 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001796 if (!NewTInfo)
1797 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001798
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001799 if (NewTInfo != OldTInfo) {
1800 // Get parameters from the new type info.
1801 TypeLoc NewTL = NewTInfo->getTypeLoc();
1802 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1803 assert(NewProtoLoc && "Missing prototype?");
1804 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1805 Params.push_back(NewProtoLoc->getArg(i));
1806 } else {
1807 // The function type itself was not dependent and therefore no
1808 // substitution occurred. However, we still need to instantiate
1809 // the function parameters themselves.
1810 TypeLoc OldTL = OldTInfo->getTypeLoc();
1811 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL);
1812 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1813 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1814 if (!Parm)
1815 return 0;
1816 Params.push_back(Parm);
1817 }
1818 }
John McCall21ef0fa2010-03-11 09:03:00 +00001819 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001820}
1821
Mike Stump1eb44332009-09-09 15:08:12 +00001822/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001823/// declaration (New) from the corresponding fields of its template (Tmpl).
1824///
1825/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001826bool
1827TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001828 FunctionDecl *Tmpl) {
1829 if (Tmpl->isDeleted())
1830 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Douglas Gregorcca9e962009-07-01 22:01:06 +00001832 // If we are performing substituting explicitly-specified template arguments
1833 // or deduced template arguments into a function template and we reach this
1834 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001835 // to keeping the new function template specialization. We therefore
1836 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001837 // into a template instantiation for this specific function template
1838 // specialization, which is not a SFINAE context, so that we diagnose any
1839 // further errors in the declaration itself.
1840 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1841 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1842 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1843 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001844 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001845 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001846 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001847 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001848 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001849 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1850 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001851 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001852 }
1853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001855 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1856 assert(Proto && "Function template without prototype?");
1857
1858 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1859 Proto->getNoReturnAttr()) {
1860 // The function has an exception specification or a "noreturn"
1861 // attribute. Substitute into each of the exception types.
1862 llvm::SmallVector<QualType, 4> Exceptions;
1863 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1864 // FIXME: Poor location information!
1865 QualType T
1866 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1867 New->getLocation(), New->getDeclName());
1868 if (T.isNull() ||
1869 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1870 continue;
1871
1872 Exceptions.push_back(T);
1873 }
1874
1875 // Rebuild the function type
1876
1877 const FunctionProtoType *NewProto
1878 = New->getType()->getAs<FunctionProtoType>();
1879 assert(NewProto && "Template instantiation without function prototype?");
1880 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1881 NewProto->arg_type_begin(),
1882 NewProto->getNumArgs(),
1883 NewProto->isVariadic(),
1884 NewProto->getTypeQuals(),
1885 Proto->hasExceptionSpec(),
1886 Proto->hasAnyExceptionSpec(),
1887 Exceptions.size(),
1888 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001889 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001890 }
1891
Douglas Gregore53060f2009-06-25 22:08:12 +00001892 return false;
1893}
1894
Douglas Gregor5545e162009-03-24 00:38:23 +00001895/// \brief Initializes common fields of an instantiated method
1896/// declaration (New) from the corresponding fields of its template
1897/// (Tmpl).
1898///
1899/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001900bool
1901TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001902 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001903 if (InitFunctionInstantiation(New, Tmpl))
1904 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregor5545e162009-03-24 00:38:23 +00001906 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1907 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001908 if (Tmpl->isVirtualAsWritten())
1909 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001910
1911 // FIXME: attributes
1912 // FIXME: New needs a pointer to Tmpl
1913 return false;
1914}
Douglas Gregora58861f2009-05-13 20:28:22 +00001915
1916/// \brief Instantiate the definition of the given function from its
1917/// template.
1918///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001919/// \param PointOfInstantiation the point at which the instantiation was
1920/// required. Note that this is not precisely a "point of instantiation"
1921/// for the function, but it's close.
1922///
Douglas Gregora58861f2009-05-13 20:28:22 +00001923/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001924/// function template specialization or member function of a class template
1925/// specialization.
1926///
1927/// \param Recursive if true, recursively instantiates any functions that
1928/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001929///
1930/// \param DefinitionRequired if true, then we are performing an explicit
1931/// instantiation where the body of the function is required. Complain if
1932/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001933void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001934 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001935 bool Recursive,
1936 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001937 if (Function->isInvalidDecl())
1938 return;
1939
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001940 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001942 // Never instantiate an explicit specialization.
1943 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1944 return;
1945
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001946 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001947 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001948 Stmt *Pattern = 0;
1949 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001950 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001951
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001952 if (!Pattern) {
1953 if (DefinitionRequired) {
1954 if (Function->getPrimaryTemplate())
1955 Diag(PointOfInstantiation,
1956 diag::err_explicit_instantiation_undefined_func_template)
1957 << Function->getPrimaryTemplate();
1958 else
1959 Diag(PointOfInstantiation,
1960 diag::err_explicit_instantiation_undefined_member)
1961 << 1 << Function->getDeclName() << Function->getDeclContext();
1962
1963 if (PatternDecl)
1964 Diag(PatternDecl->getLocation(),
1965 diag::note_explicit_instantiation_here);
1966 }
1967
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001968 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001969 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001970
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001971 // C++0x [temp.explicit]p9:
1972 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001973 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001974 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001975 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001976 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001977 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001978 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001980 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1981 if (Inst)
1982 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001983
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001984 // If we're performing recursive template instantiation, create our own
1985 // queue of pending implicit instantiations that we will instantiate later,
1986 // while we're still within our own instantiation context.
1987 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1988 if (Recursive)
1989 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001991 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1992
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001993 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001994 // recorded, unless we're actually a member function within a local
1995 // class, in which case we need to merge our results with the parent
1996 // scope (of the enclosing function).
1997 bool MergeWithParentScope = false;
1998 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1999 MergeWithParentScope = Rec->isLocalClass();
2000
2001 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002003 // Introduce the instantiated function parameters into the local
2004 // instantiation scope.
2005 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2006 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2007 Function->getParamDecl(I));
2008
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002009 // Enter the scope of this instantiation. We don't use
2010 // PushDeclContext because we don't have a scope.
2011 DeclContext *PreviousContext = CurContext;
2012 CurContext = Function;
2013
Mike Stump1eb44332009-09-09 15:08:12 +00002014 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00002015 getTemplateInstantiationArgs(Function);
2016
2017 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002018 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002019 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2020 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2021 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002022 }
2023
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002024 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002025 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002026
Douglas Gregor52604ab2009-09-11 21:19:12 +00002027 if (Body.isInvalid())
2028 Function->setInvalidDecl();
2029
Mike Stump1eb44332009-09-09 15:08:12 +00002030 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002031 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002032
John McCall0c01d182010-03-24 05:22:00 +00002033 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2034
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002035 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002036
2037 DeclGroupRef DG(Function);
2038 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Douglas Gregor60406be2010-01-16 22:29:39 +00002040 // This class may have local implicit instantiations that need to be
2041 // instantiation within this scope.
2042 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2043 Scope.Exit();
2044
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002045 if (Recursive) {
2046 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002047 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002048 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002050 // Restore the set of pending implicit instantiations.
2051 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2052 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002053}
2054
2055/// \brief Instantiate the definition of the given variable from its
2056/// template.
2057///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002058/// \param PointOfInstantiation the point at which the instantiation was
2059/// required. Note that this is not precisely a "point of instantiation"
2060/// for the function, but it's close.
2061///
2062/// \param Var the already-instantiated declaration of a static member
2063/// variable of a class template specialization.
2064///
2065/// \param Recursive if true, recursively instantiates any functions that
2066/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002067///
2068/// \param DefinitionRequired if true, then we are performing an explicit
2069/// instantiation where an out-of-line definition of the member variable
2070/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002071void Sema::InstantiateStaticDataMemberDefinition(
2072 SourceLocation PointOfInstantiation,
2073 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002074 bool Recursive,
2075 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002076 if (Var->isInvalidDecl())
2077 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregor7caa6822009-07-24 20:34:43 +00002079 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002080 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002081 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002082 assert(Def->isStaticDataMember() && "Not a static data member?");
2083 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor0d035142009-10-27 18:42:08 +00002085 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002086 // We did not find an out-of-line definition of this static data member,
2087 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002088 // instantiate this definition (or provide a specialization for it) in
2089 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002090 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002091 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002092 Diag(PointOfInstantiation,
2093 diag::err_explicit_instantiation_undefined_member)
2094 << 2 << Var->getDeclName() << Var->getDeclContext();
2095 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2096 }
2097
Douglas Gregor7caa6822009-07-24 20:34:43 +00002098 return;
2099 }
2100
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002101 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002102 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002103 return;
2104
2105 // C++0x [temp.explicit]p9:
2106 // Except for inline functions, other explicit instantiation declarations
2107 // have the effect of suppressing the implicit instantiation of the entity
2108 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002109 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002110 == TSK_ExplicitInstantiationDeclaration)
2111 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Douglas Gregor7caa6822009-07-24 20:34:43 +00002113 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2114 if (Inst)
2115 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Douglas Gregor7caa6822009-07-24 20:34:43 +00002117 // If we're performing recursive template instantiation, create our own
2118 // queue of pending implicit instantiations that we will instantiate later,
2119 // while we're still within our own instantiation context.
2120 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2121 if (Recursive)
2122 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Douglas Gregor7caa6822009-07-24 20:34:43 +00002124 // Enter the scope of this instantiation. We don't use
2125 // PushDeclContext because we don't have a scope.
2126 DeclContext *PreviousContext = CurContext;
2127 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002129 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002130 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002131 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002132 CurContext = PreviousContext;
2133
2134 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002135 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2136 assert(MSInfo && "Missing member specialization information?");
2137 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2138 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002139 DeclGroupRef DG(Var);
2140 Consumer.HandleTopLevelDecl(DG);
2141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Douglas Gregor7caa6822009-07-24 20:34:43 +00002143 if (Recursive) {
2144 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002145 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002146 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Douglas Gregor7caa6822009-07-24 20:34:43 +00002148 // Restore the set of pending implicit instantiations.
2149 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002150 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002151}
Douglas Gregor815215d2009-05-27 05:35:12 +00002152
Anders Carlsson09025312009-08-29 05:16:22 +00002153void
2154Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2155 const CXXConstructorDecl *Tmpl,
2156 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Anders Carlsson09025312009-08-29 05:16:22 +00002158 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002159 bool AnyErrors = false;
2160
Anders Carlsson09025312009-08-29 05:16:22 +00002161 // Instantiate all the initializers.
2162 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002163 InitsEnd = Tmpl->init_end();
2164 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002165 CXXBaseOrMemberInitializer *Init = *Inits;
2166
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002167 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002168 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002169 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002171 // Instantiate the initializer.
2172 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2173 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2174 AnyErrors = true;
2175 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002176 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002177
Anders Carlsson09025312009-08-29 05:16:22 +00002178 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002179 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002180 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002181 TemplateArgs,
2182 Init->getSourceLocation(),
2183 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002184 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002185 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002186 New->setInvalidDecl();
2187 continue;
2188 }
2189
John McCalla93c9342009-12-07 02:54:59 +00002190 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002191 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002192 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002193 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002194 Init->getRParenLoc(),
2195 New->getParent());
2196 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002197 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002199 // Is this an anonymous union?
2200 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002201 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2202 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002203 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002204 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2205 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002206 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002207
2208 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002209 NewArgs.size(),
2210 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002211 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002212 Init->getRParenLoc());
2213 }
2214
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002215 if (NewInit.isInvalid()) {
2216 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002217 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002218 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002219 // FIXME: It would be nice if ASTOwningVector had a release function.
2220 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Anders Carlsson09025312009-08-29 05:16:22 +00002222 NewInits.push_back((MemInitTy *)NewInit.get());
2223 }
2224 }
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Anders Carlsson09025312009-08-29 05:16:22 +00002226 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002227 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002228 /*FIXME: ColonLoc */
2229 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002230 NewInits.data(), NewInits.size(),
2231 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002232}
2233
John McCall52a575a2009-08-29 08:11:13 +00002234// TODO: this could be templated if the various decl types used the
2235// same method name.
2236static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2237 ClassTemplateDecl *Instance) {
2238 Pattern = Pattern->getCanonicalDecl();
2239
2240 do {
2241 Instance = Instance->getCanonicalDecl();
2242 if (Pattern == Instance) return true;
2243 Instance = Instance->getInstantiatedFromMemberTemplate();
2244 } while (Instance);
2245
2246 return false;
2247}
2248
Douglas Gregor0d696532009-09-28 06:34:35 +00002249static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2250 FunctionTemplateDecl *Instance) {
2251 Pattern = Pattern->getCanonicalDecl();
2252
2253 do {
2254 Instance = Instance->getCanonicalDecl();
2255 if (Pattern == Instance) return true;
2256 Instance = Instance->getInstantiatedFromMemberTemplate();
2257 } while (Instance);
2258
2259 return false;
2260}
2261
Douglas Gregored9c0f92009-10-29 00:04:11 +00002262static bool
2263isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2264 ClassTemplatePartialSpecializationDecl *Instance) {
2265 Pattern
2266 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2267 do {
2268 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2269 Instance->getCanonicalDecl());
2270 if (Pattern == Instance)
2271 return true;
2272 Instance = Instance->getInstantiatedFromMember();
2273 } while (Instance);
2274
2275 return false;
2276}
2277
John McCall52a575a2009-08-29 08:11:13 +00002278static bool isInstantiationOf(CXXRecordDecl *Pattern,
2279 CXXRecordDecl *Instance) {
2280 Pattern = Pattern->getCanonicalDecl();
2281
2282 do {
2283 Instance = Instance->getCanonicalDecl();
2284 if (Pattern == Instance) return true;
2285 Instance = Instance->getInstantiatedFromMemberClass();
2286 } while (Instance);
2287
2288 return false;
2289}
2290
2291static bool isInstantiationOf(FunctionDecl *Pattern,
2292 FunctionDecl *Instance) {
2293 Pattern = Pattern->getCanonicalDecl();
2294
2295 do {
2296 Instance = Instance->getCanonicalDecl();
2297 if (Pattern == Instance) return true;
2298 Instance = Instance->getInstantiatedFromMemberFunction();
2299 } while (Instance);
2300
2301 return false;
2302}
2303
2304static bool isInstantiationOf(EnumDecl *Pattern,
2305 EnumDecl *Instance) {
2306 Pattern = Pattern->getCanonicalDecl();
2307
2308 do {
2309 Instance = Instance->getCanonicalDecl();
2310 if (Pattern == Instance) return true;
2311 Instance = Instance->getInstantiatedFromMemberEnum();
2312 } while (Instance);
2313
2314 return false;
2315}
2316
John McCalled976492009-12-04 22:46:56 +00002317static bool isInstantiationOf(UsingShadowDecl *Pattern,
2318 UsingShadowDecl *Instance,
2319 ASTContext &C) {
2320 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2321}
2322
2323static bool isInstantiationOf(UsingDecl *Pattern,
2324 UsingDecl *Instance,
2325 ASTContext &C) {
2326 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2327}
2328
John McCall7ba107a2009-11-18 02:36:19 +00002329static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2330 UsingDecl *Instance,
2331 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002332 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002333}
2334
2335static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002336 UsingDecl *Instance,
2337 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002338 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002339}
2340
John McCall52a575a2009-08-29 08:11:13 +00002341static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2342 VarDecl *Instance) {
2343 assert(Instance->isStaticDataMember());
2344
2345 Pattern = Pattern->getCanonicalDecl();
2346
2347 do {
2348 Instance = Instance->getCanonicalDecl();
2349 if (Pattern == Instance) return true;
2350 Instance = Instance->getInstantiatedFromStaticDataMember();
2351 } while (Instance);
2352
2353 return false;
2354}
2355
John McCalled976492009-12-04 22:46:56 +00002356// Other is the prospective instantiation
2357// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002358static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002359 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002360 if (UnresolvedUsingTypenameDecl *UUD
2361 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2362 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2363 return isInstantiationOf(UUD, UD, Ctx);
2364 }
2365 }
2366
2367 if (UnresolvedUsingValueDecl *UUD
2368 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002369 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2370 return isInstantiationOf(UUD, UD, Ctx);
2371 }
2372 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002373
Anders Carlsson0d8df782009-08-29 19:37:28 +00002374 return false;
2375 }
Mike Stump1eb44332009-09-09 15:08:12 +00002376
John McCall52a575a2009-08-29 08:11:13 +00002377 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2378 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
John McCall52a575a2009-08-29 08:11:13 +00002380 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2381 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002382
John McCall52a575a2009-08-29 08:11:13 +00002383 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2384 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002385
Douglas Gregor7caa6822009-07-24 20:34:43 +00002386 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002387 if (Var->isStaticDataMember())
2388 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2389
2390 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2391 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002392
Douglas Gregor0d696532009-09-28 06:34:35 +00002393 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2394 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2395
Douglas Gregored9c0f92009-10-29 00:04:11 +00002396 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2397 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2398 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2399 PartialSpec);
2400
Anders Carlssond8b285f2009-09-01 04:26:58 +00002401 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2402 if (!Field->getDeclName()) {
2403 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002404 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002405 cast<FieldDecl>(D);
2406 }
2407 }
Mike Stump1eb44332009-09-09 15:08:12 +00002408
John McCalled976492009-12-04 22:46:56 +00002409 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2410 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2411
2412 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2413 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2414
Douglas Gregor815215d2009-05-27 05:35:12 +00002415 return D->getDeclName() && isa<NamedDecl>(Other) &&
2416 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2417}
2418
2419template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002420static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002421 NamedDecl *D,
2422 ForwardIterator first,
2423 ForwardIterator last) {
2424 for (; first != last; ++first)
2425 if (isInstantiationOf(Ctx, D, *first))
2426 return cast<NamedDecl>(*first);
2427
2428 return 0;
2429}
2430
John McCall02cace72009-08-28 07:59:38 +00002431/// \brief Finds the instantiation of the given declaration context
2432/// within the current instantiation.
2433///
2434/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002435DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002436 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002437 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002438 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002439 return cast_or_null<DeclContext>(ID);
2440 } else return DC;
2441}
2442
Douglas Gregored961e72009-05-27 17:54:46 +00002443/// \brief Find the instantiation of the given declaration within the
2444/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002445///
2446/// This routine is intended to be used when \p D is a declaration
2447/// referenced from within a template, that needs to mapped into the
2448/// corresponding declaration within an instantiation. For example,
2449/// given:
2450///
2451/// \code
2452/// template<typename T>
2453/// struct X {
2454/// enum Kind {
2455/// KnownValue = sizeof(T)
2456/// };
2457///
2458/// bool getKind() const { return KnownValue; }
2459/// };
2460///
2461/// template struct X<int>;
2462/// \endcode
2463///
2464/// In the instantiation of X<int>::getKind(), we need to map the
2465/// EnumConstantDecl for KnownValue (which refers to
2466/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002467/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2468/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002469NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002470 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002471 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002472 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002473 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002474 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002475 // D is a local of some kind. Look into the map of local
2476 // declarations to their instantiations.
2477 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2478 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002479
Douglas Gregore95b4092009-09-16 18:34:49 +00002480 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2481 if (!Record->isDependentContext())
2482 return D;
2483
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002484 // If the RecordDecl is actually the injected-class-name or a
2485 // "templated" declaration for a class template, class template
2486 // partial specialization, or a member class of a class template,
2487 // substitute into the injected-class-name of the class template
2488 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002489 QualType T;
2490 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2491
2492 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002493 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002494 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2495 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002496 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002497
2498 // If we call SubstType with an InjectedClassNameType here we
2499 // can end up in an infinite loop.
2500 T = Context.getTypeDeclType(Record);
2501 assert(isa<InjectedClassNameType>(T) &&
2502 "type of partial specialization is not an InjectedClassNameType");
2503 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2504 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002505
2506 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002507 // Substitute into the injected-class-name to get the type
2508 // corresponding to the instantiation we want, which may also be
2509 // the current instantiation (if we're in a template
2510 // definition). This substitution should never fail, since we
2511 // know we can instantiate the injected-class-name or we
2512 // wouldn't have gotten to the injected-class-name!
2513
2514 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2515 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002516 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2517 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2518
2519 if (!T->isDependentType()) {
2520 assert(T->isRecordType() && "Instantiation must produce a record type");
2521 return T->getAs<RecordType>()->getDecl();
2522 }
2523
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002524 // We are performing "partial" template instantiation to create
2525 // the member declarations for the members of a class template
2526 // specialization. Therefore, D is actually referring to something
2527 // in the current instantiation. Look through the current
2528 // context, which contains actual instantiations, to find the
2529 // instantiation of the "current instantiation" that D refers
2530 // to.
2531 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002532 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002533 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002534 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002535 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002536 if (isInstantiationOf(ClassTemplate,
2537 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002538 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002539
2540 if (!DC->isDependentContext())
2541 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002542 }
2543
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002544 // We're performing "instantiation" of a member of the current
2545 // instantiation while we are type-checking the
2546 // definition. Compute the declaration context and return that.
2547 assert(!SawNonDependentContext &&
2548 "No dependent context while instantiating record");
2549 DeclContext *DC = computeDeclContext(T);
2550 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002551 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002552 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002553 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002554
Douglas Gregore95b4092009-09-16 18:34:49 +00002555 // Fall through to deal with other dependent record types (e.g.,
2556 // anonymous unions in class templates).
2557 }
John McCall52a575a2009-08-29 08:11:13 +00002558
Douglas Gregore95b4092009-09-16 18:34:49 +00002559 if (!ParentDC->isDependentContext())
2560 return D;
2561
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002562 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002563 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002564 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Douglas Gregor815215d2009-05-27 05:35:12 +00002566 if (ParentDC != D->getDeclContext()) {
2567 // We performed some kind of instantiation in the parent context,
2568 // so now we need to look into the instantiated parent context to
2569 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002570
John McCall3cb0ebd2010-03-10 03:28:59 +00002571 // If our context used to be dependent, we may need to instantiate
2572 // it before performing lookup into that context.
2573 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002574 if (!Spec->isDependentContext()) {
2575 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002576 const RecordType *Tag = T->getAs<RecordType>();
2577 assert(Tag && "type of non-dependent record is not a RecordType");
2578 if (!Tag->isBeingDefined() &&
2579 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2580 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002581 }
2582 }
2583
Douglas Gregor815215d2009-05-27 05:35:12 +00002584 NamedDecl *Result = 0;
2585 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002586 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002587 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2588 } else {
2589 // Since we don't have a name for the entity we're looking for,
2590 // our only option is to walk through all of the declarations to
2591 // find that name. This will occur in a few cases:
2592 //
2593 // - anonymous struct/union within a template
2594 // - unnamed class/struct/union/enum within a template
2595 //
2596 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002597 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002598 ParentDC->decls_begin(),
2599 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002600 }
Mike Stump1eb44332009-09-09 15:08:12 +00002601
John McCall9f54ad42009-12-10 09:41:52 +00002602 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002603 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2604 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002605 && "Unable to find instantiation of declaration!");
2606
Douglas Gregor815215d2009-05-27 05:35:12 +00002607 D = Result;
2608 }
2609
Douglas Gregor815215d2009-05-27 05:35:12 +00002610 return D;
2611}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002612
Mike Stump1eb44332009-09-09 15:08:12 +00002613/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002614/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002615void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2616 while (!PendingLocalImplicitInstantiations.empty() ||
2617 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2618 PendingImplicitInstantiation Inst;
2619
2620 if (PendingLocalImplicitInstantiations.empty()) {
2621 Inst = PendingImplicitInstantiations.front();
2622 PendingImplicitInstantiations.pop_front();
2623 } else {
2624 Inst = PendingLocalImplicitInstantiations.front();
2625 PendingLocalImplicitInstantiations.pop_front();
2626 }
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Douglas Gregor7caa6822009-07-24 20:34:43 +00002628 // Instantiate function definitions
2629 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002630 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002631 Function->getLocation(), *this,
2632 Context.getSourceManager(),
2633 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002635 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002636 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002637 continue;
2638 }
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Douglas Gregor7caa6822009-07-24 20:34:43 +00002640 // Instantiate static data member definitions.
2641 VarDecl *Var = cast<VarDecl>(Inst.first);
2642 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002643
Chandler Carruth291b4412010-02-13 10:17:50 +00002644 // Don't try to instantiate declarations if the most recent redeclaration
2645 // is invalid.
2646 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2647 continue;
2648
2649 // Check if the most recent declaration has changed the specialization kind
2650 // and removed the need for implicit instantiation.
2651 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2652 case TSK_Undeclared:
2653 assert(false && "Cannot instantitiate an undeclared specialization.");
2654 case TSK_ExplicitInstantiationDeclaration:
2655 case TSK_ExplicitInstantiationDefinition:
2656 case TSK_ExplicitSpecialization:
2657 continue; // No longer need implicit instantiation.
2658 case TSK_ImplicitInstantiation:
2659 break;
2660 }
2661
Mike Stump1eb44332009-09-09 15:08:12 +00002662 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002663 Var->getLocation(), *this,
2664 Context.getSourceManager(),
2665 "instantiating static data member "
2666 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Douglas Gregor7caa6822009-07-24 20:34:43 +00002668 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002669 }
2670}
John McCall0c01d182010-03-24 05:22:00 +00002671
2672void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2673 const MultiLevelTemplateArgumentList &TemplateArgs) {
2674 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2675 E = Pattern->ddiag_end(); I != E; ++I) {
2676 DependentDiagnostic *DD = *I;
2677
2678 switch (DD->getKind()) {
2679 case DependentDiagnostic::Access:
2680 HandleDependentAccessCheck(*DD, TemplateArgs);
2681 break;
2682 }
2683 }
2684}