blob: 06f38e88d58d9c3cce572fec027c6543da476783 [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
Douglas Gregor4469e8a2010-05-19 17:02:24 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000035
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
Sean Hunt9a555912010-05-30 07:21:58 +000045 // clang/AST/DeclNodes.inc.
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);
Abramo Bagnara6206d532010-06-05 05:09:32 +000051 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000052 Decl *VisitFieldDecl(FieldDecl *D);
53 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
54 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000055 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000056 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000057 Decl *VisitFunctionDecl(FunctionDecl *D,
58 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000059 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000060 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
61 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000062 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000063 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000064 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000065 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000067 Decl *VisitClassTemplatePartialSpecializationDecl(
68 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000069 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000070 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000071 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000072 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000073 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000074 Decl *VisitUsingDecl(UsingDecl *D);
75 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000076 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
77 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000078
Douglas Gregor8dbc2692009-03-17 21:15:40 +000079 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000080 Decl *VisitDecl(Decl *D) {
81 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
82 Diagnostic::Error,
83 "cannot instantiate %0 yet");
84 SemaRef.Diag(D->getLocation(), DiagID)
85 << D->getDeclKindName();
86
Douglas Gregor8dbc2692009-03-17 21:15:40 +000087 return 0;
88 }
Douglas Gregor5545e162009-03-24 00:38:23 +000089
John McCallfd810b12009-08-14 02:03:10 +000090 const LangOptions &getLangOptions() {
91 return SemaRef.getLangOptions();
92 }
93
Douglas Gregor5545e162009-03-24 00:38:23 +000094 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000095 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000096 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000097 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000098 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000099
100 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000101 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000102
103 bool SubstQualifier(const DeclaratorDecl *OldDecl,
104 DeclaratorDecl *NewDecl);
105 bool SubstQualifier(const TagDecl *OldDecl,
106 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000107
108 bool InstantiateClassTemplatePartialSpecialization(
109 ClassTemplateDecl *ClassTemplate,
110 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000111 };
112}
113
John McCallb6217662010-03-15 10:12:16 +0000114bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
115 DeclaratorDecl *NewDecl) {
116 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
117 if (!OldQual) return false;
118
119 SourceRange QualRange = OldDecl->getQualifierRange();
120
121 NestedNameSpecifier *NewQual
122 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
123 if (!NewQual)
124 return true;
125
126 NewDecl->setQualifierInfo(NewQual, QualRange);
127 return false;
128}
129
130bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
131 TagDecl *NewDecl) {
132 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
133 if (!OldQual) return false;
134
135 SourceRange QualRange = OldDecl->getQualifierRange();
136
137 NestedNameSpecifier *NewQual
138 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
139 if (!NewQual)
140 return true;
141
142 NewDecl->setQualifierInfo(NewQual, QualRange);
143 return false;
144}
145
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000146// FIXME: Is this still too simple?
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000147void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000148 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000149 TmplAttr = TmplAttr->getNext()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000150 // FIXME: This should be generalized to more than just the AlignedAttr.
151 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
152 if (Aligned->isDependent()) {
153 // The alignment expression is not potentially evaluated.
154 EnterExpressionEvaluationContext Unevaluated(SemaRef,
155 Action::Unevaluated);
156
157 OwningExprResult Result = SemaRef.SubstExpr(Aligned->getAlignmentExpr(),
158 TemplateArgs);
159 if (!Result.isInvalid())
160 // FIXME: Is this the correct source location?
161 SemaRef.AddAlignedAttr(Aligned->getAlignmentExpr()->getExprLoc(),
162 New, Result.takeAs<Expr>());
163 continue;
164 }
165 }
166
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000167 // FIXME: Is cloning correct for all attributes?
168 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000169 New->addAttr(NewAttr);
170 }
171}
172
Douglas Gregor4f722be2009-03-25 15:45:12 +0000173Decl *
174TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
175 assert(false && "Translation units cannot be instantiated");
176 return D;
177}
178
179Decl *
180TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
181 assert(false && "Namespaces cannot be instantiated");
182 return D;
183}
184
John McCall3dbd3d52010-02-16 06:53:13 +0000185Decl *
186TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
187 NamespaceAliasDecl *Inst
188 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
189 D->getNamespaceLoc(),
190 D->getAliasLoc(),
191 D->getNamespace()->getIdentifier(),
192 D->getQualifierRange(),
193 D->getQualifier(),
194 D->getTargetNameLoc(),
195 D->getNamespace());
196 Owner->addDecl(Inst);
197 return Inst;
198}
199
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
201 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000202 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000203 if (DI->getType()->isDependentType() ||
204 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000205 DI = SemaRef.SubstType(DI, TemplateArgs,
206 D->getLocation(), D->getDeclName());
207 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000208 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000209 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000210 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000211 } else {
212 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000215 // Create the new typedef
216 TypedefDecl *Typedef
217 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000218 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000219 if (Invalid)
220 Typedef->setInvalidDecl();
221
Douglas Gregord57a38e2010-04-23 16:25:07 +0000222 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
223 TagDecl *TD = TT->getDecl();
224
225 // If the TagDecl that the TypedefDecl points to is an anonymous decl
226 // keep track of the TypedefDecl.
227 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
228 TD->setTypedefForAnonDecl(Typedef);
229 }
230
John McCall5126fd02009-12-30 00:31:22 +0000231 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000232 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
233 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000234 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
235 }
236
Douglas Gregora6b09072010-05-17 23:46:49 +0000237 InstantiateAttrs(D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000238
John McCall46460a62010-01-20 21:53:11 +0000239 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000240 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000242 return Typedef;
243}
244
Douglas Gregor6eef5192009-12-14 19:27:10 +0000245/// \brief Instantiate the arguments provided as part of initialization.
246///
247/// \returns true if an error occurred, false otherwise.
248static bool InstantiateInitializationArguments(Sema &SemaRef,
249 Expr **Args, unsigned NumArgs,
250 const MultiLevelTemplateArgumentList &TemplateArgs,
251 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
252 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
253 for (unsigned I = 0; I != NumArgs; ++I) {
254 // When we hit the first defaulted argument, break out of the loop:
255 // we don't pass those default arguments on.
256 if (Args[I]->isDefaultArgument())
257 break;
258
259 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
260 if (Arg.isInvalid())
261 return true;
262
263 Expr *ArgExpr = (Expr *)Arg.get();
264 InitArgs.push_back(Arg.release());
265
266 // FIXME: We're faking all of the comma locations. Do we need them?
267 FakeCommaLocs.push_back(
268 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
269 }
270
271 return false;
272}
273
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000274/// \brief Instantiate an initializer, breaking it into separate
275/// initialization arguments.
276///
277/// \param S The semantic analysis object.
278///
279/// \param Init The initializer to instantiate.
280///
281/// \param TemplateArgs Template arguments to be substituted into the
282/// initializer.
283///
284/// \param NewArgs Will be filled in with the instantiation arguments.
285///
286/// \returns true if an error occurred, false otherwise
287static bool InstantiateInitializer(Sema &S, Expr *Init,
288 const MultiLevelTemplateArgumentList &TemplateArgs,
289 SourceLocation &LParenLoc,
290 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
291 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
292 SourceLocation &RParenLoc) {
293 NewArgs.clear();
294 LParenLoc = SourceLocation();
295 RParenLoc = SourceLocation();
296
297 if (!Init)
298 return false;
299
300 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
301 Init = ExprTemp->getSubExpr();
302
303 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
304 Init = Binder->getSubExpr();
305
306 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
307 Init = ICE->getSubExprAsWritten();
308
309 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
310 LParenLoc = ParenList->getLParenLoc();
311 RParenLoc = ParenList->getRParenLoc();
312 return InstantiateInitializationArguments(S, ParenList->getExprs(),
313 ParenList->getNumExprs(),
314 TemplateArgs, CommaLocs,
315 NewArgs);
316 }
317
318 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000319 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
320 if (InstantiateInitializationArguments(S,
321 Construct->getArgs(),
322 Construct->getNumArgs(),
323 TemplateArgs,
324 CommaLocs, NewArgs))
325 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000326
Douglas Gregor28329e52010-03-24 21:22:47 +0000327 // FIXME: Fake locations!
328 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
329 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
330 return false;
331 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000332 }
333
334 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
335 if (Result.isInvalid())
336 return true;
337
338 NewArgs.push_back(Result.takeAs<Expr>());
339 return false;
340}
341
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000342Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000343 // If this is the variable for an anonymous struct or union,
344 // instantiate the anonymous struct/union type first.
345 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
346 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
347 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
348 return 0;
349
John McCallce3ff2b2009-08-25 22:02:44 +0000350 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000351 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000352 TemplateArgs,
353 D->getTypeSpecStartLoc(),
354 D->getDeclName());
355 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000356 return 0;
357
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000358 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000359 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
360 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000361 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000362 D->getStorageClass(),
363 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000364 Var->setThreadSpecified(D->isThreadSpecified());
365 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
366 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000367
John McCallb6217662010-03-15 10:12:16 +0000368 // Substitute the nested name specifier, if any.
369 if (SubstQualifier(D, Var))
370 return 0;
371
Mike Stump1eb44332009-09-09 15:08:12 +0000372 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000373 // out-of-line, the instantiation will have the same lexical
374 // context (which will be a namespace scope) as the template.
375 if (D->isOutOfLine())
376 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000377
John McCall46460a62010-01-20 21:53:11 +0000378 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000379
380 if (!D->isStaticDataMember())
381 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000382
Mike Stump390b4cc2009-05-16 07:39:55 +0000383 // FIXME: In theory, we could have a previous declaration for variables that
384 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000385 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000386 // FIXME: having to fake up a LookupResult is dumb.
387 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000388 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000389 if (D->isStaticDataMember())
390 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000391 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregor7caa6822009-07-24 20:34:43 +0000393 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000394 if (!D->isStaticDataMember())
395 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000396 Owner->makeDeclVisibleInContext(Var);
397 } else {
398 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000399
400 if (Owner->isFunctionOrMethod())
401 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000404 // Link instantiations of static data members back to the template from
405 // which they were instantiated.
406 if (Var->isStaticDataMember())
407 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000408 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000409
Douglas Gregor60c93c92010-02-09 07:26:29 +0000410 if (Var->getAnyInitializer()) {
411 // We already have an initializer in the class.
412 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413 if (Var->isStaticDataMember() && !D->isOutOfLine())
414 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
415 else
416 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
417
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000418 // Instantiate the initializer.
419 SourceLocation LParenLoc, RParenLoc;
420 llvm::SmallVector<SourceLocation, 4> CommaLocs;
421 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
422 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
423 CommaLocs, InitArgs, RParenLoc)) {
424 // Attach the initializer to the declaration.
425 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000426 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000427 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000428 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000429 move_arg(InitArgs),
430 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000431 RParenLoc);
432 } else if (InitArgs.size() == 1) {
433 Expr *Init = (Expr*)(InitArgs.take()[0]);
434 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
435 SemaRef.Owned(Init),
436 false);
437 } else {
438 assert(InitArgs.size() == 0);
439 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000440 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000441 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000442 // FIXME: Not too happy about invalidating the declaration
443 // because of a bogus initializer.
444 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000445 }
446
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000447 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000448 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
449 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000450
Douglas Gregor5764f612010-05-08 23:05:03 +0000451 // Diagnose unused local variables.
452 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
453 SemaRef.DiagnoseUnusedDecl(Var);
454
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000455 return Var;
456}
457
Abramo Bagnara6206d532010-06-05 05:09:32 +0000458Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
459 AccessSpecDecl* AD
460 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
461 D->getAccessSpecifierLoc(), D->getColonLoc());
462 Owner->addHiddenDecl(AD);
463 return AD;
464}
465
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000466Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
467 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000468 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000469 if (DI->getType()->isDependentType() ||
470 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000471 DI = SemaRef.SubstType(DI, TemplateArgs,
472 D->getLocation(), D->getDeclName());
473 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000474 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000475 Invalid = true;
476 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000477 // C++ [temp.arg.type]p3:
478 // If a declaration acquires a function type through a type
479 // dependent on a template-parameter and this causes a
480 // declaration that does not use the syntactic form of a
481 // function declarator to have function type, the program is
482 // ill-formed.
483 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000484 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485 Invalid = true;
486 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000487 } else {
488 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000489 }
490
491 Expr *BitWidth = D->getBitWidth();
492 if (Invalid)
493 BitWidth = 0;
494 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000495 // The bit-width expression is not potentially evaluated.
496 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000498 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000499 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000500 if (InstantiatedBitWidth.isInvalid()) {
501 Invalid = true;
502 BitWidth = 0;
503 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000504 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000505 }
506
John McCall07fb6be2009-10-22 23:33:21 +0000507 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
508 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000509 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000510 D->getLocation(),
511 D->isMutable(),
512 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000513 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000514 D->getAccess(),
515 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000516 if (!Field) {
517 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000518 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000521 InstantiateAttrs(D, Field);
522
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000523 if (Invalid)
524 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000526 if (!Field->getDeclName()) {
527 // Keep track of where this decl came from.
528 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000529 }
530 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
531 if (Parent->isAnonymousStructOrUnion() &&
532 Parent->getLookupContext()->isFunctionOrMethod())
533 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000536 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000537 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000538 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000539
540 return Field;
541}
542
John McCall02cace72009-08-28 07:59:38 +0000543Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000544 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000545 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000546 if (TypeSourceInfo *Ty = D->getFriendType()) {
547 TypeSourceInfo *InstTy =
548 SemaRef.SubstType(Ty, TemplateArgs,
549 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000550 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000551 return 0;
John McCall02cace72009-08-28 07:59:38 +0000552
Douglas Gregor06245bf2010-04-07 17:57:12 +0000553 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
554 if (!FD)
555 return 0;
556
557 FD->setAccess(AS_public);
558 Owner->addDecl(FD);
559 return FD;
560 }
561
562 NamedDecl *ND = D->getFriendDecl();
563 assert(ND && "friend decl must be a decl or a type!");
564
John McCallaf2094e2010-04-08 09:05:18 +0000565 // All of the Visit implementations for the various potential friend
566 // declarations have to be carefully written to work for friend
567 // objects, with the most important detail being that the target
568 // decl should almost certainly not be placed in Owner.
569 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000570 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000571
John McCall02cace72009-08-28 07:59:38 +0000572 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000573 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
574 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000575 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000576 Owner->addDecl(FD);
577 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000578}
579
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000580Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
581 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Douglas Gregorac7610d2009-06-22 20:57:11 +0000583 // The expression in a static assertion is not potentially evaluated.
584 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000587 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588 if (InstantiatedAssertExpr.isInvalid())
589 return 0;
590
Douglas Gregor43d9d922009-08-08 01:41:12 +0000591 OwningExprResult Message(SemaRef, D->getMessage());
592 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000593 Decl *StaticAssert
594 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000595 move(InstantiatedAssertExpr),
596 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000597 return StaticAssert;
598}
599
600Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000601 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000603 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000605 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000606 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000607 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000608 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000609 Enum->startDefinition();
610
Douglas Gregor96084f12010-03-01 19:00:07 +0000611 if (D->getDeclContext()->isFunctionOrMethod())
612 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
613
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000614 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000615
616 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000617 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
618 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000619 EC != ECEnd; ++EC) {
620 // The specified value for the enumerator.
621 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000622 if (Expr *UninstValue = EC->getInitExpr()) {
623 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000624 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000625 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000626
John McCallce3ff2b2009-08-25 22:02:44 +0000627 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000628 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000629
630 // Drop the initial value and continue.
631 bool isInvalid = false;
632 if (Value.isInvalid()) {
633 Value = SemaRef.Owned((Expr *)0);
634 isInvalid = true;
635 }
636
Mike Stump1eb44332009-09-09 15:08:12 +0000637 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000638 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
639 EC->getLocation(), EC->getIdentifier(),
640 move(Value));
641
642 if (isInvalid) {
643 if (EnumConst)
644 EnumConst->setInvalidDecl();
645 Enum->setInvalidDecl();
646 }
647
648 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000649 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000650 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000651 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000652 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000653
654 if (D->getDeclContext()->isFunctionOrMethod()) {
655 // If the enumeration is within a function or method, record the enum
656 // constant as a local.
657 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
658 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000659 }
660 }
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000662 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000663 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000664 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
665 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000666 &Enumerators[0], Enumerators.size(),
667 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000668
669 return Enum;
670}
671
Douglas Gregor6477b692009-03-25 15:04:13 +0000672Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
673 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
674 return 0;
675}
676
John McCalle29ba202009-08-20 01:44:21 +0000677Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000678 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
679
Douglas Gregor550d9b22009-10-31 17:21:17 +0000680 // Create a local instantiation scope for this class template, which
681 // will contain the instantiations of the template parameters.
682 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000683 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000684 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000685 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000686 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000687
688 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000689
690 // Instantiate the qualifier. We have to do this first in case
691 // we're a friend declaration, because if we are then we need to put
692 // the new declaration in the appropriate context.
693 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
694 if (Qualifier) {
695 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
696 Pattern->getQualifierRange(),
697 TemplateArgs);
698 if (!Qualifier) return 0;
699 }
700
701 CXXRecordDecl *PrevDecl = 0;
702 ClassTemplateDecl *PrevClassTemplate = 0;
703
704 // If this isn't a friend, then it's a member template, in which
705 // case we just want to build the instantiation in the
706 // specialization. If it is a friend, we want to build it in
707 // the appropriate context.
708 DeclContext *DC = Owner;
709 if (isFriend) {
710 if (Qualifier) {
711 CXXScopeSpec SS;
712 SS.setScopeRep(Qualifier);
713 SS.setRange(Pattern->getQualifierRange());
714 DC = SemaRef.computeDeclContext(SS);
715 if (!DC) return 0;
716 } else {
717 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
718 Pattern->getDeclContext(),
719 TemplateArgs);
720 }
721
722 // Look for a previous declaration of the template in the owning
723 // context.
724 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
725 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
726 SemaRef.LookupQualifiedName(R, DC);
727
728 if (R.isSingleResult()) {
729 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
730 if (PrevClassTemplate)
731 PrevDecl = PrevClassTemplate->getTemplatedDecl();
732 }
733
734 if (!PrevClassTemplate && Qualifier) {
735 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000736 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
737 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000738 return 0;
739 }
740
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000741 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000742 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000743 bool Complain = true;
744
745 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
746 // template for struct std::tr1::__detail::_Map_base, where the
747 // template parameters of the friend declaration don't match the
748 // template parameters of the original declaration. In this one
749 // case, we don't complain about the ill-formed friend
750 // declaration.
751 if (isFriend && Pattern->getIdentifier() &&
752 Pattern->getIdentifier()->isStr("_Map_base") &&
753 DC->isNamespace() &&
754 cast<NamespaceDecl>(DC)->getIdentifier() &&
755 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
756 DeclContext *DCParent = DC->getParent();
757 if (DCParent->isNamespace() &&
758 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
759 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
760 DeclContext *DCParent2 = DCParent->getParent();
761 if (DCParent2->isNamespace() &&
762 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
763 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
764 DCParent2->getParent()->isTranslationUnit())
765 Complain = false;
766 }
767 }
768
John McCall93ba8572010-03-25 06:39:04 +0000769 TemplateParameterList *PrevParams
770 = PrevClassTemplate->getTemplateParameters();
771
772 // Make sure the parameter lists match.
773 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000774 Complain,
775 Sema::TPL_TemplateMatch)) {
776 if (Complain)
777 return 0;
778
779 AdoptedPreviousTemplateParams = true;
780 InstParams = PrevParams;
781 }
John McCall93ba8572010-03-25 06:39:04 +0000782
783 // Do some additional validation, then merge default arguments
784 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000785 if (!AdoptedPreviousTemplateParams &&
786 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000787 Sema::TPC_ClassTemplate))
788 return 0;
789 }
790 }
791
John McCalle29ba202009-08-20 01:44:21 +0000792 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000793 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000794 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000795 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000796 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000797
John McCall93ba8572010-03-25 06:39:04 +0000798 if (Qualifier)
799 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000800
John McCalle29ba202009-08-20 01:44:21 +0000801 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000802 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
803 D->getIdentifier(), InstParams, RecordInst,
804 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000805 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000806
John McCall93ba8572010-03-25 06:39:04 +0000807 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000808 if (PrevClassTemplate)
809 Inst->setAccess(PrevClassTemplate->getAccess());
810 else
811 Inst->setAccess(D->getAccess());
812
John McCall93ba8572010-03-25 06:39:04 +0000813 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
814 // TODO: do we want to track the instantiation progeny of this
815 // friend target decl?
816 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000817 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000818 Inst->setInstantiatedFromMemberTemplate(D);
819 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000820
821 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000822 SemaRef.Context.getInjectedClassNameType(RecordInst,
823 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000824
Douglas Gregor259571e2009-10-30 22:42:42 +0000825 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000826 if (isFriend) {
827 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000828 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000829 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000830
John McCalle29ba202009-08-20 01:44:21 +0000831 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000832
Douglas Gregored9c0f92009-10-29 00:04:11 +0000833 // Instantiate all of the partial specializations of this member class
834 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000835 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
836 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000837 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
838 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
839
John McCalle29ba202009-08-20 01:44:21 +0000840 return Inst;
841}
842
Douglas Gregord60e1052009-08-27 16:57:43 +0000843Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000844TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
845 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000846 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
847
848 // Lookup the already-instantiated declaration in the instantiation
849 // of the class template and return that.
850 DeclContext::lookup_result Found
851 = Owner->lookup(ClassTemplate->getDeclName());
852 if (Found.first == Found.second)
853 return 0;
854
855 ClassTemplateDecl *InstClassTemplate
856 = dyn_cast<ClassTemplateDecl>(*Found.first);
857 if (!InstClassTemplate)
858 return 0;
859
860 Decl *DCanon = D->getCanonicalDecl();
861 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
862 P = InstClassTemplate->getPartialSpecializations().begin(),
863 PEnd = InstClassTemplate->getPartialSpecializations().end();
864 P != PEnd; ++P) {
865 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
866 return &*P;
867 }
868
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000869 return 0;
870}
871
872Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000873TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000874 // Create a local instantiation scope for this function template, which
875 // will contain the instantiations of the template parameters and then get
876 // merged with the local instantiation scope for the function template
877 // itself.
878 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000879
Douglas Gregord60e1052009-08-27 16:57:43 +0000880 TemplateParameterList *TempParams = D->getTemplateParameters();
881 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000882 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000883 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000884
Douglas Gregora735b202009-10-13 14:39:41 +0000885 FunctionDecl *Instantiated = 0;
886 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
887 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
888 InstParams));
889 else
890 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
891 D->getTemplatedDecl(),
892 InstParams));
893
894 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000895 return 0;
896
John McCall46460a62010-01-20 21:53:11 +0000897 Instantiated->setAccess(D->getAccess());
898
Mike Stump1eb44332009-09-09 15:08:12 +0000899 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000900 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000901 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000902 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000903 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000904 assert(InstTemplate &&
905 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000906
John McCallb1a56e72010-03-26 23:10:15 +0000907 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
908
John McCalle976ffe2009-12-14 23:19:40 +0000909 // Link the instantiation back to the pattern *unless* this is a
910 // non-definition friend declaration.
911 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000912 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000913 InstTemplate->setInstantiatedFromMemberTemplate(D);
914
John McCallb1a56e72010-03-26 23:10:15 +0000915 // Make declarations visible in the appropriate context.
916 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000917 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000918
Douglas Gregord60e1052009-08-27 16:57:43 +0000919 return InstTemplate;
920}
921
Douglas Gregord475b8d2009-03-25 21:17:03 +0000922Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
923 CXXRecordDecl *PrevDecl = 0;
924 if (D->isInjectedClassName())
925 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000926 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000927 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
928 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000929 TemplateArgs);
930 if (!Prev) return 0;
931 PrevDecl = cast<CXXRecordDecl>(Prev);
932 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000933
934 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000935 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000936 D->getLocation(), D->getIdentifier(),
937 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000938
939 // Substitute the nested name specifier, if any.
940 if (SubstQualifier(D, Record))
941 return 0;
942
Douglas Gregord475b8d2009-03-25 21:17:03 +0000943 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000944 // FIXME: Check against AS_none is an ugly hack to work around the issue that
945 // the tag decls introduced by friend class declarations don't have an access
946 // specifier. Remove once this area of the code gets sorted out.
947 if (D->getAccess() != AS_none)
948 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000949 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000950 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000951
John McCall02cace72009-08-28 07:59:38 +0000952 // If the original function was part of a friend declaration,
953 // inherit its namespace state.
954 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
955 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
956
Douglas Gregor9901c572010-05-21 00:31:19 +0000957 // Make sure that anonymous structs and unions are recorded.
958 if (D->isAnonymousStructOrUnion()) {
959 Record->setAnonymousStructOrUnion(true);
960 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod())
961 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
962 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000963
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000964 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000965 return Record;
966}
967
John McCall02cace72009-08-28 07:59:38 +0000968/// Normal class members are of more specific types and therefore
969/// don't make it here. This function serves two purposes:
970/// 1) instantiating function templates
971/// 2) substituting friend declarations
972/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000973Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000974 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000975 // Check whether there is already a function template specialization for
976 // this declaration.
977 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
978 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000979 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000980 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000981 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000982 TemplateArgs.getInnermost().getFlatArgumentList(),
983 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000984 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000985
986 FunctionTemplateSpecializationInfo *Info
987 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000988 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Douglas Gregor127102b2009-06-29 20:59:39 +0000990 // If we already have a function template specialization, return it.
991 if (Info)
992 return Info->Function;
993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
John McCallb0cb0222010-03-27 05:57:59 +0000995 bool isFriend;
996 if (FunctionTemplate)
997 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
998 else
999 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1000
Douglas Gregor79c22782010-01-16 20:21:20 +00001001 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001002 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +00001003 !(isa<Decl>(Owner) &&
1004 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1005 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Douglas Gregore53060f2009-06-25 22:08:12 +00001007 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001008 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1009 TInfo = SubstFunctionType(D, Params);
1010 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001011 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001012 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001013
John McCalld325daa2010-03-26 04:53:08 +00001014 NestedNameSpecifier *Qualifier = D->getQualifier();
1015 if (Qualifier) {
1016 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1017 D->getQualifierRange(),
1018 TemplateArgs);
1019 if (!Qualifier) return 0;
1020 }
1021
John McCall68b6b872010-02-06 01:50:47 +00001022 // If we're instantiating a local function declaration, put the result
1023 // in the owner; otherwise we need to find the instantiated context.
1024 DeclContext *DC;
1025 if (D->getDeclContext()->isFunctionOrMethod())
1026 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001027 else if (isFriend && Qualifier) {
1028 CXXScopeSpec SS;
1029 SS.setScopeRep(Qualifier);
1030 SS.setRange(D->getQualifierRange());
1031 DC = SemaRef.computeDeclContext(SS);
1032 if (!DC) return 0;
1033 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001034 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1035 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001036 }
John McCall68b6b872010-02-06 01:50:47 +00001037
John McCall02cace72009-08-28 07:59:38 +00001038 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001039 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001040 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001041 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001042 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001043
John McCalld325daa2010-03-26 04:53:08 +00001044 if (Qualifier)
1045 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001046
John McCallb1a56e72010-03-26 23:10:15 +00001047 DeclContext *LexicalDC = Owner;
1048 if (!isFriend && D->isOutOfLine()) {
1049 assert(D->getDeclContext()->isFileContext());
1050 LexicalDC = D->getDeclContext();
1051 }
1052
1053 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregore53060f2009-06-25 22:08:12 +00001055 // Attach the parameters
1056 for (unsigned P = 0; P < Params.size(); ++P)
1057 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001058 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001059
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001060 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001061 if (TemplateParams) {
1062 // Our resulting instantiation is actually a function template, since we
1063 // are substituting only the outer template parameters. For example, given
1064 //
1065 // template<typename T>
1066 // struct X {
1067 // template<typename U> friend void f(T, U);
1068 // };
1069 //
1070 // X<int> x;
1071 //
1072 // We are instantiating the friend function template "f" within X<int>,
1073 // which means substituting int for T, but leaving "f" as a friend function
1074 // template.
1075 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001076 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001077 Function->getLocation(),
1078 Function->getDeclName(),
1079 TemplateParams, Function);
1080 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001081
1082 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001083
1084 if (isFriend && D->isThisDeclarationADefinition()) {
1085 // TODO: should we remember this connection regardless of whether
1086 // the friend declaration provided a body?
1087 FunctionTemplate->setInstantiatedFromMemberTemplate(
1088 D->getDescribedFunctionTemplate());
1089 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001090 } else if (FunctionTemplate) {
1091 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001092 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001093 &TemplateArgs.getInnermost(),
1094 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001095 } else if (isFriend && D->isThisDeclarationADefinition()) {
1096 // TODO: should we remember this connection regardless of whether
1097 // the friend declaration provided a body?
1098 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001099 }
Douglas Gregora735b202009-10-13 14:39:41 +00001100
Douglas Gregore53060f2009-06-25 22:08:12 +00001101 if (InitFunctionInstantiation(Function, D))
1102 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Douglas Gregore53060f2009-06-25 22:08:12 +00001104 bool Redeclaration = false;
1105 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001106 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001107
John McCall68263142009-11-18 22:49:29 +00001108 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1109 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1110
John McCallaf2094e2010-04-08 09:05:18 +00001111 if (DependentFunctionTemplateSpecializationInfo *Info
1112 = D->getDependentSpecializationInfo()) {
1113 assert(isFriend && "non-friend has dependent specialization info?");
1114
1115 // This needs to be set now for future sanity.
1116 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1117
1118 // Instantiate the explicit template arguments.
1119 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1120 Info->getRAngleLoc());
1121 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1122 TemplateArgumentLoc Loc;
1123 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1124 return 0;
1125
1126 ExplicitArgs.addArgument(Loc);
1127 }
1128
1129 // Map the candidate templates to their instantiations.
1130 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1131 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1132 Info->getTemplate(I),
1133 TemplateArgs);
1134 if (!Temp) return 0;
1135
1136 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1137 }
1138
1139 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1140 &ExplicitArgs,
1141 Previous))
1142 Function->setInvalidDecl();
1143
1144 isExplicitSpecialization = true;
1145
1146 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001147 // Look only into the namespace where the friend would be declared to
1148 // find a previous declaration. This is the innermost enclosing namespace,
1149 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001150 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001151
Douglas Gregora735b202009-10-13 14:39:41 +00001152 // In C++, the previous declaration we find might be a tag type
1153 // (class or enum). In this case, the new declaration will hide the
1154 // tag type. Note that this does does not apply if we're declaring a
1155 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001156 if (Previous.isSingleTagDecl())
1157 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001158 }
1159
John McCall9f54ad42009-12-10 09:41:52 +00001160 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001161 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001162 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001163
John McCall76d32642010-04-24 01:30:58 +00001164 NamedDecl *PrincipalDecl = (TemplateParams
1165 ? cast<NamedDecl>(FunctionTemplate)
1166 : Function);
1167
Douglas Gregora735b202009-10-13 14:39:41 +00001168 // If the original function was part of a friend declaration,
1169 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001170 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001171 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001172 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001173 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001174 else
Douglas Gregora735b202009-10-13 14:39:41 +00001175 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001176
1177 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1178 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001179
1180 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1181 D->isThisDeclarationADefinition()) {
1182 // Check for a function body.
1183 const FunctionDecl *Definition = 0;
1184 if (Function->getBody(Definition) &&
1185 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1186 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1187 << Function->getDeclName();
1188 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1189 Function->setInvalidDecl();
1190 }
1191 // Check for redefinitions due to other instantiations of this or
1192 // a similar friend function.
1193 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1194 REnd = Function->redecls_end();
1195 R != REnd; ++R) {
1196 if (*R != Function &&
1197 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1198 if (const FunctionDecl *RPattern
1199 = (*R)->getTemplateInstantiationPattern())
1200 if (RPattern->getBody(RPattern)) {
1201 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1202 << Function->getDeclName();
1203 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1204 Function->setInvalidDecl();
1205 break;
1206 }
1207 }
1208 }
1209 }
1210
Douglas Gregora735b202009-10-13 14:39:41 +00001211 }
1212
John McCall76d32642010-04-24 01:30:58 +00001213 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1214 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1215 PrincipalDecl->setNonMemberOperator();
1216
Douglas Gregore53060f2009-06-25 22:08:12 +00001217 return Function;
1218}
1219
Douglas Gregord60e1052009-08-27 16:57:43 +00001220Decl *
1221TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1222 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001223 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1224 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001225 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001226 // We are creating a function template specialization from a function
1227 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001228 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001229 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001230 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001231 TemplateArgs.getInnermost().getFlatArgumentList(),
1232 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001233 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
1235 FunctionTemplateSpecializationInfo *Info
1236 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001237 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregor6b906862009-08-21 00:16:32 +00001239 // If we already have a function template specialization, return it.
1240 if (Info)
1241 return Info->Function;
1242 }
1243
John McCallb0cb0222010-03-27 05:57:59 +00001244 bool isFriend;
1245 if (FunctionTemplate)
1246 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1247 else
1248 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1249
Douglas Gregor79c22782010-01-16 20:21:20 +00001250 bool MergeWithParentScope = (TemplateParams != 0) ||
1251 !(isa<Decl>(Owner) &&
1252 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1253 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001254
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001255 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001256 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1257 TInfo = SubstFunctionType(D, Params);
1258 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001259 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001260 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001261
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001262 // \brief If the type of this function is not *directly* a function
1263 // type, then we're instantiating the a function that was declared
1264 // via a typedef, e.g.,
1265 //
1266 // typedef int functype(int, int);
1267 // functype func;
1268 //
1269 // In this case, we'll just go instantiate the ParmVarDecls that we
1270 // synthesized in the method declaration.
1271 if (!isa<FunctionProtoType>(T)) {
1272 assert(!Params.size() && "Instantiating type could not yield parameters");
1273 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1274 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1275 TemplateArgs);
1276 if (!P)
1277 return 0;
1278
1279 Params.push_back(P);
1280 }
1281 }
1282
John McCallb0cb0222010-03-27 05:57:59 +00001283 NestedNameSpecifier *Qualifier = D->getQualifier();
1284 if (Qualifier) {
1285 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1286 D->getQualifierRange(),
1287 TemplateArgs);
1288 if (!Qualifier) return 0;
1289 }
1290
1291 DeclContext *DC = Owner;
1292 if (isFriend) {
1293 if (Qualifier) {
1294 CXXScopeSpec SS;
1295 SS.setScopeRep(Qualifier);
1296 SS.setRange(D->getQualifierRange());
1297 DC = SemaRef.computeDeclContext(SS);
1298 } else {
1299 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1300 D->getDeclContext(),
1301 TemplateArgs);
1302 }
1303 if (!DC) return 0;
1304 }
1305
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001306 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001307 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001308 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Douglas Gregordec06662009-08-21 18:42:58 +00001310 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001311 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001312 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1313 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1314 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001315 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1316 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001317 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001319 Constructor->isInlineSpecified(),
1320 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001321 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1322 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1323 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1324 SemaRef.Context.getCanonicalType(ClassTy));
1325 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1326 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001327 T, Destructor->isInlineSpecified(),
1328 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001329 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001330 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001331 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001332 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001333 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1334 ConvTy);
1335 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1336 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001337 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001338 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001339 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001340 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001341 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001342 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001343 D->isStatic(),
1344 D->getStorageClassAsWritten(),
1345 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001346 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001347
John McCallb0cb0222010-03-27 05:57:59 +00001348 if (Qualifier)
1349 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001350
Douglas Gregord60e1052009-08-27 16:57:43 +00001351 if (TemplateParams) {
1352 // Our resulting instantiation is actually a function template, since we
1353 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001354 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001355 // template<typename T>
1356 // struct X {
1357 // template<typename U> void f(T, U);
1358 // };
1359 //
1360 // X<int> x;
1361 //
1362 // We are instantiating the member template "f" within X<int>, which means
1363 // substituting int for T, but leaving "f" as a member function template.
1364 // Build the function template itself.
1365 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1366 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001367 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001368 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001369 if (isFriend) {
1370 FunctionTemplate->setLexicalDeclContext(Owner);
1371 FunctionTemplate->setObjectOfFriendDecl(true);
1372 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001373 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001374 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001375 } else if (FunctionTemplate) {
1376 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001377 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001378 &TemplateArgs.getInnermost(),
1379 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001380 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001381 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001382 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001383 }
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001386 // out-of-line, the instantiation will have the same lexical
1387 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001388 if (isFriend) {
1389 Method->setLexicalDeclContext(Owner);
1390 Method->setObjectOfFriendDecl(true);
1391 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001392 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor5545e162009-03-24 00:38:23 +00001394 // Attach the parameters
1395 for (unsigned P = 0; P < Params.size(); ++P)
1396 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001397 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001398
1399 if (InitMethodInstantiation(Method, D))
1400 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001401
John McCall68263142009-11-18 22:49:29 +00001402 LookupResult Previous(SemaRef, Name, SourceLocation(),
1403 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001404
John McCallb0cb0222010-03-27 05:57:59 +00001405 if (!FunctionTemplate || TemplateParams || isFriend) {
1406 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregordec06662009-08-21 18:42:58 +00001408 // In C++, the previous declaration we find might be a tag type
1409 // (class or enum). In this case, the new declaration will hide the
1410 // tag type. Note that this does does not apply if we're declaring a
1411 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001412 if (Previous.isSingleTagDecl())
1413 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001414 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001415
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001416 bool Redeclaration = false;
1417 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001418 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001419 /*FIXME:*/OverloadableAttrRequired);
1420
Douglas Gregor4ba31362009-12-01 17:24:26 +00001421 if (D->isPure())
1422 SemaRef.CheckPureMethod(Method, SourceRange());
1423
John McCall46460a62010-01-20 21:53:11 +00001424 Method->setAccess(D->getAccess());
1425
John McCallb0cb0222010-03-27 05:57:59 +00001426 if (FunctionTemplate) {
1427 // If there's a function template, let our caller handle it.
1428 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1429 // Don't hide a (potentially) valid declaration with an invalid one.
1430 } else {
1431 NamedDecl *DeclToAdd = (TemplateParams
1432 ? cast<NamedDecl>(FunctionTemplate)
1433 : Method);
1434 if (isFriend)
1435 Record->makeDeclVisibleInContext(DeclToAdd);
1436 else
1437 Owner->addDecl(DeclToAdd);
1438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001440 return Method;
1441}
1442
Douglas Gregor615c5d42009-03-24 16:43:20 +00001443Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001444 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001445}
1446
Douglas Gregor03b2b072009-03-24 00:15:49 +00001447Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001448 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001449}
1450
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001451Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001452 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001453}
1454
Douglas Gregor6477b692009-03-25 15:04:13 +00001455ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001456 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001457}
1458
John McCalle29ba202009-08-20 01:44:21 +00001459Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1460 TemplateTypeParmDecl *D) {
1461 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001462 const Type* T = D->getTypeForDecl();
1463 assert(T->isTemplateTypeParmType());
1464 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001465
John McCalle29ba202009-08-20 01:44:21 +00001466 TemplateTypeParmDecl *Inst =
1467 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001468 TTPT->getDepth() - 1, TTPT->getIndex(),
1469 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001470 D->wasDeclaredWithTypename(),
1471 D->isParameterPack());
1472
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001473 if (D->hasDefaultArgument())
1474 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001475
Douglas Gregor550d9b22009-10-31 17:21:17 +00001476 // Introduce this template parameter's instantiation into the instantiation
1477 // scope.
1478 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1479
John McCalle29ba202009-08-20 01:44:21 +00001480 return Inst;
1481}
1482
Douglas Gregor33642df2009-10-23 23:25:44 +00001483Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1484 NonTypeTemplateParmDecl *D) {
1485 // Substitute into the type of the non-type template parameter.
1486 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001487 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001488 if (DI) {
1489 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1490 D->getDeclName());
1491 if (DI) T = DI->getType();
1492 } else {
1493 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1494 D->getDeclName());
1495 DI = 0;
1496 }
1497 if (T.isNull())
1498 return 0;
1499
1500 // Check that this type is acceptable for a non-type template parameter.
1501 bool Invalid = false;
1502 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1503 if (T.isNull()) {
1504 T = SemaRef.Context.IntTy;
1505 Invalid = true;
1506 }
1507
1508 NonTypeTemplateParmDecl *Param
1509 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1510 D->getDepth() - 1, D->getPosition(),
1511 D->getIdentifier(), T, DI);
1512 if (Invalid)
1513 Param->setInvalidDecl();
1514
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001515 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001516
1517 // Introduce this template parameter's instantiation into the instantiation
1518 // scope.
1519 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001520 return Param;
1521}
1522
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001523Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001524TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1525 TemplateTemplateParmDecl *D) {
1526 // Instantiate the template parameter list of the template template parameter.
1527 TemplateParameterList *TempParams = D->getTemplateParameters();
1528 TemplateParameterList *InstParams;
1529 {
1530 // Perform the actual substitution of template parameters within a new,
1531 // local instantiation scope.
1532 Sema::LocalInstantiationScope Scope(SemaRef);
1533 InstParams = SubstTemplateParams(TempParams);
1534 if (!InstParams)
1535 return NULL;
1536 }
1537
1538 // Build the template template parameter.
1539 TemplateTemplateParmDecl *Param
1540 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1541 D->getDepth() - 1, D->getPosition(),
1542 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001543 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001544
Douglas Gregor9106ef72009-11-11 16:58:32 +00001545 // Introduce this template parameter's instantiation into the instantiation
1546 // scope.
1547 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1548
1549 return Param;
1550}
1551
Douglas Gregor48c32a72009-11-17 06:07:40 +00001552Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1553 // Using directives are never dependent, so they require no explicit
1554
1555 UsingDirectiveDecl *Inst
1556 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1557 D->getNamespaceKeyLocation(),
1558 D->getQualifierRange(), D->getQualifier(),
1559 D->getIdentLocation(),
1560 D->getNominatedNamespace(),
1561 D->getCommonAncestor());
1562 Owner->addDecl(Inst);
1563 return Inst;
1564}
1565
John McCalled976492009-12-04 22:46:56 +00001566Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1567 // The nested name specifier is non-dependent, so no transformation
1568 // is required.
1569
John McCall9f54ad42009-12-10 09:41:52 +00001570 // We only need to do redeclaration lookups if we're in a class
1571 // scope (in fact, it's not really even possible in non-class
1572 // scopes).
1573 bool CheckRedeclaration = Owner->isRecord();
1574
1575 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1576 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1577
John McCalled976492009-12-04 22:46:56 +00001578 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1579 D->getLocation(),
1580 D->getNestedNameRange(),
1581 D->getUsingLocation(),
1582 D->getTargetNestedNameDecl(),
1583 D->getDeclName(),
1584 D->isTypeName());
1585
1586 CXXScopeSpec SS;
1587 SS.setScopeRep(D->getTargetNestedNameDecl());
1588 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001589
1590 if (CheckRedeclaration) {
1591 Prev.setHideTags(false);
1592 SemaRef.LookupQualifiedName(Prev, Owner);
1593
1594 // Check for invalid redeclarations.
1595 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1596 D->isTypeName(), SS,
1597 D->getLocation(), Prev))
1598 NewUD->setInvalidDecl();
1599
1600 }
1601
1602 if (!NewUD->isInvalidDecl() &&
1603 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001604 D->getLocation()))
1605 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001606
John McCalled976492009-12-04 22:46:56 +00001607 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1608 NewUD->setAccess(D->getAccess());
1609 Owner->addDecl(NewUD);
1610
John McCall9f54ad42009-12-10 09:41:52 +00001611 // Don't process the shadow decls for an invalid decl.
1612 if (NewUD->isInvalidDecl())
1613 return NewUD;
1614
John McCall323c3102009-12-22 22:26:37 +00001615 bool isFunctionScope = Owner->isFunctionOrMethod();
1616
John McCall9f54ad42009-12-10 09:41:52 +00001617 // Process the shadow decls.
1618 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1619 I != E; ++I) {
1620 UsingShadowDecl *Shadow = *I;
1621 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001622 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1623 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001624 TemplateArgs));
1625
1626 if (CheckRedeclaration &&
1627 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1628 continue;
1629
1630 UsingShadowDecl *InstShadow
1631 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1632 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001633
1634 if (isFunctionScope)
1635 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001636 }
John McCalled976492009-12-04 22:46:56 +00001637
1638 return NewUD;
1639}
1640
1641Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001642 // Ignore these; we handle them in bulk when processing the UsingDecl.
1643 return 0;
John McCalled976492009-12-04 22:46:56 +00001644}
1645
John McCall7ba107a2009-11-18 02:36:19 +00001646Decl * TemplateDeclInstantiator
1647 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001648 NestedNameSpecifier *NNS =
1649 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1650 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001651 TemplateArgs);
1652 if (!NNS)
1653 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001655 CXXScopeSpec SS;
1656 SS.setRange(D->getTargetNestedNameRange());
1657 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
1659 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001660 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001661 D->getUsingLoc(), SS, D->getLocation(),
1662 D->getDeclName(), 0,
1663 /*instantiation*/ true,
1664 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001665 if (UD)
John McCalled976492009-12-04 22:46:56 +00001666 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1667
John McCall7ba107a2009-11-18 02:36:19 +00001668 return UD;
1669}
1670
1671Decl * TemplateDeclInstantiator
1672 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1673 NestedNameSpecifier *NNS =
1674 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1675 D->getTargetNestedNameRange(),
1676 TemplateArgs);
1677 if (!NNS)
1678 return 0;
1679
1680 CXXScopeSpec SS;
1681 SS.setRange(D->getTargetNestedNameRange());
1682 SS.setScopeRep(NNS);
1683
1684 NamedDecl *UD =
1685 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1686 D->getUsingLoc(), SS, D->getLocation(),
1687 D->getDeclName(), 0,
1688 /*instantiation*/ true,
1689 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001690 if (UD)
John McCalled976492009-12-04 22:46:56 +00001691 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1692
Anders Carlsson0d8df782009-08-29 19:37:28 +00001693 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001694}
1695
John McCallce3ff2b2009-08-25 22:02:44 +00001696Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001697 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001698 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001699 if (D->isInvalidDecl())
1700 return 0;
1701
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001702 return Instantiator.Visit(D);
1703}
1704
John McCalle29ba202009-08-20 01:44:21 +00001705/// \brief Instantiates a nested template parameter list in the current
1706/// instantiation context.
1707///
1708/// \param L The parameter list to instantiate
1709///
1710/// \returns NULL if there was an error
1711TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001712TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001713 // Get errors for all the parameters before bailing out.
1714 bool Invalid = false;
1715
1716 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001717 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001718 ParamVector Params;
1719 Params.reserve(N);
1720 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1721 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001722 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001723 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001724 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001725 }
1726
1727 // Clean up if we had an error.
1728 if (Invalid) {
1729 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1730 PI != PE; ++PI)
1731 if (*PI)
1732 (*PI)->Destroy(SemaRef.Context);
1733 return NULL;
1734 }
1735
1736 TemplateParameterList *InstL
1737 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1738 L->getLAngleLoc(), &Params.front(), N,
1739 L->getRAngleLoc());
1740 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001741}
John McCalle29ba202009-08-20 01:44:21 +00001742
Douglas Gregored9c0f92009-10-29 00:04:11 +00001743/// \brief Instantiate the declaration of a class template partial
1744/// specialization.
1745///
1746/// \param ClassTemplate the (instantiated) class template that is partially
1747// specialized by the instantiation of \p PartialSpec.
1748///
1749/// \param PartialSpec the (uninstantiated) class template partial
1750/// specialization that we are instantiating.
1751///
1752/// \returns true if there was an error, false otherwise.
1753bool
1754TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1755 ClassTemplateDecl *ClassTemplate,
1756 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001757 // Create a local instantiation scope for this class template partial
1758 // specialization, which will contain the instantiations of the template
1759 // parameters.
1760 Sema::LocalInstantiationScope Scope(SemaRef);
1761
Douglas Gregored9c0f92009-10-29 00:04:11 +00001762 // Substitute into the template parameters of the class template partial
1763 // specialization.
1764 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1765 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1766 if (!InstParams)
1767 return true;
1768
1769 // Substitute into the template arguments of the class template partial
1770 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001771 const TemplateArgumentLoc *PartialSpecTemplateArgs
1772 = PartialSpec->getTemplateArgsAsWritten();
1773 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1774
John McCalld5532b62009-11-23 01:53:49 +00001775 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001776 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001777 TemplateArgumentLoc Loc;
1778 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001779 return true;
John McCalld5532b62009-11-23 01:53:49 +00001780 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001781 }
1782
1783
1784 // Check that the template argument list is well-formed for this
1785 // class template.
1786 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1787 InstTemplateArgs.size());
1788 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1789 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001790 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001791 false,
1792 Converted))
1793 return true;
1794
1795 // Figure out where to insert this class template partial specialization
1796 // in the member template's set of class template partial specializations.
1797 llvm::FoldingSetNodeID ID;
1798 ClassTemplatePartialSpecializationDecl::Profile(ID,
1799 Converted.getFlatArguments(),
1800 Converted.flatSize(),
1801 SemaRef.Context);
1802 void *InsertPos = 0;
1803 ClassTemplateSpecializationDecl *PrevDecl
1804 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1805 InsertPos);
1806
1807 // Build the canonical type that describes the converted template
1808 // arguments of the class template partial specialization.
1809 QualType CanonType
1810 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1811 Converted.getFlatArguments(),
1812 Converted.flatSize());
1813
1814 // Build the fully-sugared type for this class template
1815 // specialization as the user wrote in the specialization
1816 // itself. This means that we'll pretty-print the type retrieved
1817 // from the specialization's declaration the way that the user
1818 // actually wrote the specialization, rather than formatting the
1819 // name based on the "canonical" representation used to store the
1820 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001821 TypeSourceInfo *WrittenTy
1822 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1823 TemplateName(ClassTemplate),
1824 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001825 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001826 CanonType);
1827
1828 if (PrevDecl) {
1829 // We've already seen a partial specialization with the same template
1830 // parameters and template arguments. This can happen, for example, when
1831 // substituting the outer template arguments ends up causing two
1832 // class template partial specializations of a member class template
1833 // to have identical forms, e.g.,
1834 //
1835 // template<typename T, typename U>
1836 // struct Outer {
1837 // template<typename X, typename Y> struct Inner;
1838 // template<typename Y> struct Inner<T, Y>;
1839 // template<typename Y> struct Inner<U, Y>;
1840 // };
1841 //
1842 // Outer<int, int> outer; // error: the partial specializations of Inner
1843 // // have the same signature.
1844 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1845 << WrittenTy;
1846 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1847 << SemaRef.Context.getTypeDeclType(PrevDecl);
1848 return true;
1849 }
1850
1851
1852 // Create the class template partial specialization declaration.
1853 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001854 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1855 PartialSpec->getTagKind(),
1856 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001857 PartialSpec->getLocation(),
1858 InstParams,
1859 ClassTemplate,
1860 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001861 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001862 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001863 0,
1864 ClassTemplate->getPartialSpecializations().size());
John McCallb6217662010-03-15 10:12:16 +00001865 // Substitute the nested name specifier, if any.
1866 if (SubstQualifier(PartialSpec, InstPartialSpec))
1867 return 0;
1868
Douglas Gregored9c0f92009-10-29 00:04:11 +00001869 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001870 InstPartialSpec->setTypeAsWritten(WrittenTy);
1871
Douglas Gregored9c0f92009-10-29 00:04:11 +00001872 // Add this partial specialization to the set of class template partial
1873 // specializations.
1874 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1875 InsertPos);
1876 return false;
1877}
1878
John McCall21ef0fa2010-03-11 09:03:00 +00001879TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001880TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001881 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001882 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1883 assert(OldTInfo && "substituting function without type source info");
1884 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001885 TypeSourceInfo *NewTInfo
1886 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1887 D->getTypeSpecStartLoc(),
1888 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001889 if (!NewTInfo)
1890 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001891
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001892 if (NewTInfo != OldTInfo) {
1893 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001894 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001895 if (FunctionProtoTypeLoc *OldProtoLoc
1896 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1897 TypeLoc NewTL = NewTInfo->getTypeLoc();
1898 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1899 assert(NewProtoLoc && "Missing prototype?");
1900 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1901 // FIXME: Variadic templates will break this.
1902 Params.push_back(NewProtoLoc->getArg(i));
1903 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001904 OldProtoLoc->getArg(i),
1905 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001906 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001907 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001908 } else {
1909 // The function type itself was not dependent and therefore no
1910 // substitution occurred. However, we still need to instantiate
1911 // the function parameters themselves.
1912 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001913 if (FunctionProtoTypeLoc *OldProtoLoc
1914 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1915 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1916 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1917 if (!Parm)
1918 return 0;
1919 Params.push_back(Parm);
1920 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001921 }
1922 }
John McCall21ef0fa2010-03-11 09:03:00 +00001923 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001924}
1925
Mike Stump1eb44332009-09-09 15:08:12 +00001926/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001927/// declaration (New) from the corresponding fields of its template (Tmpl).
1928///
1929/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001930bool
1931TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001932 FunctionDecl *Tmpl) {
1933 if (Tmpl->isDeleted())
1934 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregorcca9e962009-07-01 22:01:06 +00001936 // If we are performing substituting explicitly-specified template arguments
1937 // or deduced template arguments into a function template and we reach this
1938 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001939 // to keeping the new function template specialization. We therefore
1940 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001941 // into a template instantiation for this specific function template
1942 // specialization, which is not a SFINAE context, so that we diagnose any
1943 // further errors in the declaration itself.
1944 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1945 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1946 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1947 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001948 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001949 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001950 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001951 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001952 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001953 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1954 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001955 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001956 }
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001959 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1960 assert(Proto && "Function template without prototype?");
1961
1962 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1963 Proto->getNoReturnAttr()) {
1964 // The function has an exception specification or a "noreturn"
1965 // attribute. Substitute into each of the exception types.
1966 llvm::SmallVector<QualType, 4> Exceptions;
1967 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1968 // FIXME: Poor location information!
1969 QualType T
1970 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1971 New->getLocation(), New->getDeclName());
1972 if (T.isNull() ||
1973 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1974 continue;
1975
1976 Exceptions.push_back(T);
1977 }
1978
1979 // Rebuild the function type
1980
1981 const FunctionProtoType *NewProto
1982 = New->getType()->getAs<FunctionProtoType>();
1983 assert(NewProto && "Template instantiation without function prototype?");
1984 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1985 NewProto->arg_type_begin(),
1986 NewProto->getNumArgs(),
1987 NewProto->isVariadic(),
1988 NewProto->getTypeQuals(),
1989 Proto->hasExceptionSpec(),
1990 Proto->hasAnyExceptionSpec(),
1991 Exceptions.size(),
1992 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001993 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001994 }
1995
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001996 InstantiateAttrs(Tmpl, New);
1997
Douglas Gregore53060f2009-06-25 22:08:12 +00001998 return false;
1999}
2000
Douglas Gregor5545e162009-03-24 00:38:23 +00002001/// \brief Initializes common fields of an instantiated method
2002/// declaration (New) from the corresponding fields of its template
2003/// (Tmpl).
2004///
2005/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002006bool
2007TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002008 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002009 if (InitFunctionInstantiation(New, Tmpl))
2010 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregor5545e162009-03-24 00:38:23 +00002012 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
2013 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002014 if (Tmpl->isVirtualAsWritten())
2015 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00002016
2017 // FIXME: attributes
2018 // FIXME: New needs a pointer to Tmpl
2019 return false;
2020}
Douglas Gregora58861f2009-05-13 20:28:22 +00002021
2022/// \brief Instantiate the definition of the given function from its
2023/// template.
2024///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002025/// \param PointOfInstantiation the point at which the instantiation was
2026/// required. Note that this is not precisely a "point of instantiation"
2027/// for the function, but it's close.
2028///
Douglas Gregora58861f2009-05-13 20:28:22 +00002029/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002030/// function template specialization or member function of a class template
2031/// specialization.
2032///
2033/// \param Recursive if true, recursively instantiates any functions that
2034/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002035///
2036/// \param DefinitionRequired if true, then we are performing an explicit
2037/// instantiation where the body of the function is required. Complain if
2038/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002039void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002040 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002041 bool Recursive,
2042 bool DefinitionRequired) {
Douglas Gregor238058c2010-05-18 05:45:02 +00002043 if (Function->isInvalidDecl() || Function->getBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002044 return;
2045
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002046 // Never instantiate an explicit specialization.
2047 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2048 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002049
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002050 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002051 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002052 Stmt *Pattern = 0;
2053 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002054 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002055
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002056 if (!Pattern) {
2057 if (DefinitionRequired) {
2058 if (Function->getPrimaryTemplate())
2059 Diag(PointOfInstantiation,
2060 diag::err_explicit_instantiation_undefined_func_template)
2061 << Function->getPrimaryTemplate();
2062 else
2063 Diag(PointOfInstantiation,
2064 diag::err_explicit_instantiation_undefined_member)
2065 << 1 << Function->getDeclName() << Function->getDeclContext();
2066
2067 if (PatternDecl)
2068 Diag(PatternDecl->getLocation(),
2069 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002070 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002071 }
2072
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002073 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002074 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002075
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002076 // C++0x [temp.explicit]p9:
2077 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002078 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002079 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002080 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002081 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002082 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002085 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2086 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002087 return;
2088
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002089 // If we're performing recursive template instantiation, create our own
2090 // queue of pending implicit instantiations that we will instantiate later,
2091 // while we're still within our own instantiation context.
2092 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2093 if (Recursive)
2094 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Douglas Gregor9679caf2010-05-12 17:27:19 +00002096 EnterExpressionEvaluationContext EvalContext(*this,
2097 Action::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002098 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2099
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002100 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002101 // recorded, unless we're actually a member function within a local
2102 // class, in which case we need to merge our results with the parent
2103 // scope (of the enclosing function).
2104 bool MergeWithParentScope = false;
2105 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2106 MergeWithParentScope = Rec->isLocalClass();
2107
2108 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002110 // Introduce the instantiated function parameters into the local
2111 // instantiation scope.
2112 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2113 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2114 Function->getParamDecl(I));
2115
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002116 // Enter the scope of this instantiation. We don't use
2117 // PushDeclContext because we don't have a scope.
2118 DeclContext *PreviousContext = CurContext;
2119 CurContext = Function;
2120
Mike Stump1eb44332009-09-09 15:08:12 +00002121 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002122 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002123
2124 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002125 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002126 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2127 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2128 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002129 }
2130
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002131 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002132 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002133
Douglas Gregor52604ab2009-09-11 21:19:12 +00002134 if (Body.isInvalid())
2135 Function->setInvalidDecl();
2136
Mike Stump1eb44332009-09-09 15:08:12 +00002137 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002138 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002139
John McCall0c01d182010-03-24 05:22:00 +00002140 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2141
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002142 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002143
2144 DeclGroupRef DG(Function);
2145 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Douglas Gregor60406be2010-01-16 22:29:39 +00002147 // This class may have local implicit instantiations that need to be
2148 // instantiation within this scope.
2149 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2150 Scope.Exit();
2151
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002152 if (Recursive) {
2153 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002154 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002155 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002157 // Restore the set of pending implicit instantiations.
2158 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2159 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002160}
2161
2162/// \brief Instantiate the definition of the given variable from its
2163/// template.
2164///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002165/// \param PointOfInstantiation the point at which the instantiation was
2166/// required. Note that this is not precisely a "point of instantiation"
2167/// for the function, but it's close.
2168///
2169/// \param Var the already-instantiated declaration of a static member
2170/// variable of a class template specialization.
2171///
2172/// \param Recursive if true, recursively instantiates any functions that
2173/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002174///
2175/// \param DefinitionRequired if true, then we are performing an explicit
2176/// instantiation where an out-of-line definition of the member variable
2177/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002178void Sema::InstantiateStaticDataMemberDefinition(
2179 SourceLocation PointOfInstantiation,
2180 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002181 bool Recursive,
2182 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002183 if (Var->isInvalidDecl())
2184 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Douglas Gregor7caa6822009-07-24 20:34:43 +00002186 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002187 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002188 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002189 assert(Def->isStaticDataMember() && "Not a static data member?");
2190 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Douglas Gregor0d035142009-10-27 18:42:08 +00002192 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002193 // We did not find an out-of-line definition of this static data member,
2194 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002195 // instantiate this definition (or provide a specialization for it) in
2196 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002197 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002198 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002199 Diag(PointOfInstantiation,
2200 diag::err_explicit_instantiation_undefined_member)
2201 << 2 << Var->getDeclName() << Var->getDeclContext();
2202 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2203 }
2204
Douglas Gregor7caa6822009-07-24 20:34:43 +00002205 return;
2206 }
2207
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002208 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002209 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002210 return;
2211
2212 // C++0x [temp.explicit]p9:
2213 // Except for inline functions, other explicit instantiation declarations
2214 // have the effect of suppressing the implicit instantiation of the entity
2215 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002216 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002217 == TSK_ExplicitInstantiationDeclaration)
2218 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor7caa6822009-07-24 20:34:43 +00002220 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2221 if (Inst)
2222 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregor7caa6822009-07-24 20:34:43 +00002224 // If we're performing recursive template instantiation, create our own
2225 // queue of pending implicit instantiations that we will instantiate later,
2226 // while we're still within our own instantiation context.
2227 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2228 if (Recursive)
2229 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor7caa6822009-07-24 20:34:43 +00002231 // Enter the scope of this instantiation. We don't use
2232 // PushDeclContext because we don't have a scope.
2233 DeclContext *PreviousContext = CurContext;
2234 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002236 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002237 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002238 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002239 CurContext = PreviousContext;
2240
2241 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002242 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2243 assert(MSInfo && "Missing member specialization information?");
2244 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2245 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002246 DeclGroupRef DG(Var);
2247 Consumer.HandleTopLevelDecl(DG);
2248 }
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregor7caa6822009-07-24 20:34:43 +00002250 if (Recursive) {
2251 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002253 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor7caa6822009-07-24 20:34:43 +00002255 // Restore the set of pending implicit instantiations.
2256 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002257 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002258}
Douglas Gregor815215d2009-05-27 05:35:12 +00002259
Anders Carlsson09025312009-08-29 05:16:22 +00002260void
2261Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2262 const CXXConstructorDecl *Tmpl,
2263 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Anders Carlsson09025312009-08-29 05:16:22 +00002265 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002266 bool AnyErrors = false;
2267
Anders Carlsson09025312009-08-29 05:16:22 +00002268 // Instantiate all the initializers.
2269 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002270 InitsEnd = Tmpl->init_end();
2271 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002272 CXXBaseOrMemberInitializer *Init = *Inits;
2273
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002274 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002275 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002276 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002278 // Instantiate the initializer.
2279 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2280 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2281 AnyErrors = true;
2282 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002283 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002284
Anders Carlsson09025312009-08-29 05:16:22 +00002285 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002286 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002287 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002288 TemplateArgs,
2289 Init->getSourceLocation(),
2290 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002291 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002292 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002293 New->setInvalidDecl();
2294 continue;
2295 }
2296
John McCalla93c9342009-12-07 02:54:59 +00002297 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002298 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002299 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002300 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002301 Init->getRParenLoc(),
2302 New->getParent());
2303 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002304 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002306 // Is this an anonymous union?
2307 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002308 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2309 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002310 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002311 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2312 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002313 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002314
2315 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002316 NewArgs.size(),
2317 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002318 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002319 Init->getRParenLoc());
2320 }
2321
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002322 if (NewInit.isInvalid()) {
2323 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002324 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002325 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002326 // FIXME: It would be nice if ASTOwningVector had a release function.
2327 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Anders Carlsson09025312009-08-29 05:16:22 +00002329 NewInits.push_back((MemInitTy *)NewInit.get());
2330 }
2331 }
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Anders Carlsson09025312009-08-29 05:16:22 +00002333 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002334 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002335 /*FIXME: ColonLoc */
2336 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002337 NewInits.data(), NewInits.size(),
2338 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002339}
2340
John McCall52a575a2009-08-29 08:11:13 +00002341// TODO: this could be templated if the various decl types used the
2342// same method name.
2343static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2344 ClassTemplateDecl *Instance) {
2345 Pattern = Pattern->getCanonicalDecl();
2346
2347 do {
2348 Instance = Instance->getCanonicalDecl();
2349 if (Pattern == Instance) return true;
2350 Instance = Instance->getInstantiatedFromMemberTemplate();
2351 } while (Instance);
2352
2353 return false;
2354}
2355
Douglas Gregor0d696532009-09-28 06:34:35 +00002356static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2357 FunctionTemplateDecl *Instance) {
2358 Pattern = Pattern->getCanonicalDecl();
2359
2360 do {
2361 Instance = Instance->getCanonicalDecl();
2362 if (Pattern == Instance) return true;
2363 Instance = Instance->getInstantiatedFromMemberTemplate();
2364 } while (Instance);
2365
2366 return false;
2367}
2368
Douglas Gregored9c0f92009-10-29 00:04:11 +00002369static bool
2370isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2371 ClassTemplatePartialSpecializationDecl *Instance) {
2372 Pattern
2373 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2374 do {
2375 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2376 Instance->getCanonicalDecl());
2377 if (Pattern == Instance)
2378 return true;
2379 Instance = Instance->getInstantiatedFromMember();
2380 } while (Instance);
2381
2382 return false;
2383}
2384
John McCall52a575a2009-08-29 08:11:13 +00002385static bool isInstantiationOf(CXXRecordDecl *Pattern,
2386 CXXRecordDecl *Instance) {
2387 Pattern = Pattern->getCanonicalDecl();
2388
2389 do {
2390 Instance = Instance->getCanonicalDecl();
2391 if (Pattern == Instance) return true;
2392 Instance = Instance->getInstantiatedFromMemberClass();
2393 } while (Instance);
2394
2395 return false;
2396}
2397
2398static bool isInstantiationOf(FunctionDecl *Pattern,
2399 FunctionDecl *Instance) {
2400 Pattern = Pattern->getCanonicalDecl();
2401
2402 do {
2403 Instance = Instance->getCanonicalDecl();
2404 if (Pattern == Instance) return true;
2405 Instance = Instance->getInstantiatedFromMemberFunction();
2406 } while (Instance);
2407
2408 return false;
2409}
2410
2411static bool isInstantiationOf(EnumDecl *Pattern,
2412 EnumDecl *Instance) {
2413 Pattern = Pattern->getCanonicalDecl();
2414
2415 do {
2416 Instance = Instance->getCanonicalDecl();
2417 if (Pattern == Instance) return true;
2418 Instance = Instance->getInstantiatedFromMemberEnum();
2419 } while (Instance);
2420
2421 return false;
2422}
2423
John McCalled976492009-12-04 22:46:56 +00002424static bool isInstantiationOf(UsingShadowDecl *Pattern,
2425 UsingShadowDecl *Instance,
2426 ASTContext &C) {
2427 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2428}
2429
2430static bool isInstantiationOf(UsingDecl *Pattern,
2431 UsingDecl *Instance,
2432 ASTContext &C) {
2433 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2434}
2435
John McCall7ba107a2009-11-18 02:36:19 +00002436static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2437 UsingDecl *Instance,
2438 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002439 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002440}
2441
2442static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002443 UsingDecl *Instance,
2444 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002445 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002446}
2447
John McCall52a575a2009-08-29 08:11:13 +00002448static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2449 VarDecl *Instance) {
2450 assert(Instance->isStaticDataMember());
2451
2452 Pattern = Pattern->getCanonicalDecl();
2453
2454 do {
2455 Instance = Instance->getCanonicalDecl();
2456 if (Pattern == Instance) return true;
2457 Instance = Instance->getInstantiatedFromStaticDataMember();
2458 } while (Instance);
2459
2460 return false;
2461}
2462
John McCalled976492009-12-04 22:46:56 +00002463// Other is the prospective instantiation
2464// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002465static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002466 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002467 if (UnresolvedUsingTypenameDecl *UUD
2468 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2469 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2470 return isInstantiationOf(UUD, UD, Ctx);
2471 }
2472 }
2473
2474 if (UnresolvedUsingValueDecl *UUD
2475 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002476 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2477 return isInstantiationOf(UUD, UD, Ctx);
2478 }
2479 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002480
Anders Carlsson0d8df782009-08-29 19:37:28 +00002481 return false;
2482 }
Mike Stump1eb44332009-09-09 15:08:12 +00002483
John McCall52a575a2009-08-29 08:11:13 +00002484 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2485 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002486
John McCall52a575a2009-08-29 08:11:13 +00002487 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2488 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002489
John McCall52a575a2009-08-29 08:11:13 +00002490 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2491 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002492
Douglas Gregor7caa6822009-07-24 20:34:43 +00002493 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002494 if (Var->isStaticDataMember())
2495 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2496
2497 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2498 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002499
Douglas Gregor0d696532009-09-28 06:34:35 +00002500 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2501 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2502
Douglas Gregored9c0f92009-10-29 00:04:11 +00002503 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2504 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2505 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2506 PartialSpec);
2507
Anders Carlssond8b285f2009-09-01 04:26:58 +00002508 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2509 if (!Field->getDeclName()) {
2510 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002511 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002512 cast<FieldDecl>(D);
2513 }
2514 }
Mike Stump1eb44332009-09-09 15:08:12 +00002515
John McCalled976492009-12-04 22:46:56 +00002516 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2517 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2518
2519 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2520 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2521
Douglas Gregor815215d2009-05-27 05:35:12 +00002522 return D->getDeclName() && isa<NamedDecl>(Other) &&
2523 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2524}
2525
2526template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002527static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002528 NamedDecl *D,
2529 ForwardIterator first,
2530 ForwardIterator last) {
2531 for (; first != last; ++first)
2532 if (isInstantiationOf(Ctx, D, *first))
2533 return cast<NamedDecl>(*first);
2534
2535 return 0;
2536}
2537
John McCall02cace72009-08-28 07:59:38 +00002538/// \brief Finds the instantiation of the given declaration context
2539/// within the current instantiation.
2540///
2541/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002542DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002543 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002544 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002545 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002546 return cast_or_null<DeclContext>(ID);
2547 } else return DC;
2548}
2549
Douglas Gregored961e72009-05-27 17:54:46 +00002550/// \brief Find the instantiation of the given declaration within the
2551/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002552///
2553/// This routine is intended to be used when \p D is a declaration
2554/// referenced from within a template, that needs to mapped into the
2555/// corresponding declaration within an instantiation. For example,
2556/// given:
2557///
2558/// \code
2559/// template<typename T>
2560/// struct X {
2561/// enum Kind {
2562/// KnownValue = sizeof(T)
2563/// };
2564///
2565/// bool getKind() const { return KnownValue; }
2566/// };
2567///
2568/// template struct X<int>;
2569/// \endcode
2570///
2571/// In the instantiation of X<int>::getKind(), we need to map the
2572/// EnumConstantDecl for KnownValue (which refers to
2573/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002574/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2575/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002576NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002577 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002578 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002579 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002580 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002581 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002582 // D is a local of some kind. Look into the map of local
2583 // declarations to their instantiations.
2584 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2585 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002586
Douglas Gregore95b4092009-09-16 18:34:49 +00002587 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2588 if (!Record->isDependentContext())
2589 return D;
2590
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002591 // If the RecordDecl is actually the injected-class-name or a
2592 // "templated" declaration for a class template, class template
2593 // partial specialization, or a member class of a class template,
2594 // substitute into the injected-class-name of the class template
2595 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002596 QualType T;
2597 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2598
2599 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002600 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002601 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2602 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002603 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002604
2605 // If we call SubstType with an InjectedClassNameType here we
2606 // can end up in an infinite loop.
2607 T = Context.getTypeDeclType(Record);
2608 assert(isa<InjectedClassNameType>(T) &&
2609 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002610 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002611 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002612
2613 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002614 // Substitute into the injected-class-name to get the type
2615 // corresponding to the instantiation we want, which may also be
2616 // the current instantiation (if we're in a template
2617 // definition). This substitution should never fail, since we
2618 // know we can instantiate the injected-class-name or we
2619 // wouldn't have gotten to the injected-class-name!
2620
2621 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2622 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002623 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2624 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2625
2626 if (!T->isDependentType()) {
2627 assert(T->isRecordType() && "Instantiation must produce a record type");
2628 return T->getAs<RecordType>()->getDecl();
2629 }
2630
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002631 // We are performing "partial" template instantiation to create
2632 // the member declarations for the members of a class template
2633 // specialization. Therefore, D is actually referring to something
2634 // in the current instantiation. Look through the current
2635 // context, which contains actual instantiations, to find the
2636 // instantiation of the "current instantiation" that D refers
2637 // to.
2638 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002639 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002640 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002641 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002642 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002643 if (isInstantiationOf(ClassTemplate,
2644 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002645 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002646
2647 if (!DC->isDependentContext())
2648 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002649 }
2650
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002651 // We're performing "instantiation" of a member of the current
2652 // instantiation while we are type-checking the
2653 // definition. Compute the declaration context and return that.
2654 assert(!SawNonDependentContext &&
2655 "No dependent context while instantiating record");
2656 DeclContext *DC = computeDeclContext(T);
2657 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002658 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002659 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002660 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002661
Douglas Gregore95b4092009-09-16 18:34:49 +00002662 // Fall through to deal with other dependent record types (e.g.,
2663 // anonymous unions in class templates).
2664 }
John McCall52a575a2009-08-29 08:11:13 +00002665
Douglas Gregore95b4092009-09-16 18:34:49 +00002666 if (!ParentDC->isDependentContext())
2667 return D;
2668
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002669 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002670 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002671 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Douglas Gregor815215d2009-05-27 05:35:12 +00002673 if (ParentDC != D->getDeclContext()) {
2674 // We performed some kind of instantiation in the parent context,
2675 // so now we need to look into the instantiated parent context to
2676 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002677
John McCall3cb0ebd2010-03-10 03:28:59 +00002678 // If our context used to be dependent, we may need to instantiate
2679 // it before performing lookup into that context.
2680 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002681 if (!Spec->isDependentContext()) {
2682 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002683 const RecordType *Tag = T->getAs<RecordType>();
2684 assert(Tag && "type of non-dependent record is not a RecordType");
2685 if (!Tag->isBeingDefined() &&
2686 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2687 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002688 }
2689 }
2690
Douglas Gregor815215d2009-05-27 05:35:12 +00002691 NamedDecl *Result = 0;
2692 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002693 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002694 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2695 } else {
2696 // Since we don't have a name for the entity we're looking for,
2697 // our only option is to walk through all of the declarations to
2698 // find that name. This will occur in a few cases:
2699 //
2700 // - anonymous struct/union within a template
2701 // - unnamed class/struct/union/enum within a template
2702 //
2703 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002704 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002705 ParentDC->decls_begin(),
2706 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002707 }
Mike Stump1eb44332009-09-09 15:08:12 +00002708
John McCall9f54ad42009-12-10 09:41:52 +00002709 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002710 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2711 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002712 && "Unable to find instantiation of declaration!");
2713
Douglas Gregor815215d2009-05-27 05:35:12 +00002714 D = Result;
2715 }
2716
Douglas Gregor815215d2009-05-27 05:35:12 +00002717 return D;
2718}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002719
Mike Stump1eb44332009-09-09 15:08:12 +00002720/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002721/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002722void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2723 while (!PendingLocalImplicitInstantiations.empty() ||
2724 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2725 PendingImplicitInstantiation Inst;
2726
2727 if (PendingLocalImplicitInstantiations.empty()) {
2728 Inst = PendingImplicitInstantiations.front();
2729 PendingImplicitInstantiations.pop_front();
2730 } else {
2731 Inst = PendingLocalImplicitInstantiations.front();
2732 PendingLocalImplicitInstantiations.pop_front();
2733 }
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Douglas Gregor7caa6822009-07-24 20:34:43 +00002735 // Instantiate function definitions
2736 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002737 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002738 Function->getLocation(), *this,
2739 Context.getSourceManager(),
2740 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002742 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002743 continue;
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Douglas Gregor7caa6822009-07-24 20:34:43 +00002746 // Instantiate static data member definitions.
2747 VarDecl *Var = cast<VarDecl>(Inst.first);
2748 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002749
Chandler Carruth291b4412010-02-13 10:17:50 +00002750 // Don't try to instantiate declarations if the most recent redeclaration
2751 // is invalid.
2752 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2753 continue;
2754
2755 // Check if the most recent declaration has changed the specialization kind
2756 // and removed the need for implicit instantiation.
2757 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2758 case TSK_Undeclared:
2759 assert(false && "Cannot instantitiate an undeclared specialization.");
2760 case TSK_ExplicitInstantiationDeclaration:
2761 case TSK_ExplicitInstantiationDefinition:
2762 case TSK_ExplicitSpecialization:
2763 continue; // No longer need implicit instantiation.
2764 case TSK_ImplicitInstantiation:
2765 break;
2766 }
2767
Mike Stump1eb44332009-09-09 15:08:12 +00002768 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002769 Var->getLocation(), *this,
2770 Context.getSourceManager(),
2771 "instantiating static data member "
2772 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Douglas Gregor7caa6822009-07-24 20:34:43 +00002774 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002775 }
2776}
John McCall0c01d182010-03-24 05:22:00 +00002777
2778void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2779 const MultiLevelTemplateArgumentList &TemplateArgs) {
2780 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2781 E = Pattern->ddiag_end(); I != E; ++I) {
2782 DependentDiagnostic *DD = *I;
2783
2784 switch (DD->getKind()) {
2785 case DependentDiagnostic::Access:
2786 HandleDependentAccessCheck(*DD, TemplateArgs);
2787 break;
2788 }
2789 }
2790}