blob: 5778a827fcfe167d9894c843701399598f2bf73b [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,
Douglas Gregor24bae922010-07-08 18:37:38 +0000823 Inst->getInjectedClassNameSpecialization());
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;
Douglas Gregor24bae922010-07-08 18:37:38 +0000981 std::pair<const TemplateArgument *, unsigned> Innermost
982 = TemplateArgs.getInnermost();
983 FunctionTemplateSpecializationInfo::Profile(ID, Innermost.first,
984 Innermost.second,
Douglas Gregor828e2262009-07-29 16:09:57 +0000985 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000986
987 FunctionTemplateSpecializationInfo *Info
988 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000989 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Douglas Gregor127102b2009-06-29 20:59:39 +0000991 // If we already have a function template specialization, return it.
992 if (Info)
993 return Info->Function;
994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
John McCallb0cb0222010-03-27 05:57:59 +0000996 bool isFriend;
997 if (FunctionTemplate)
998 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
999 else
1000 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1001
Douglas Gregor79c22782010-01-16 20:21:20 +00001002 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001003 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +00001004 !(isa<Decl>(Owner) &&
1005 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1006 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregore53060f2009-06-25 22:08:12 +00001008 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001009 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1010 TInfo = SubstFunctionType(D, Params);
1011 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001012 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001013 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001014
John McCalld325daa2010-03-26 04:53:08 +00001015 NestedNameSpecifier *Qualifier = D->getQualifier();
1016 if (Qualifier) {
1017 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1018 D->getQualifierRange(),
1019 TemplateArgs);
1020 if (!Qualifier) return 0;
1021 }
1022
John McCall68b6b872010-02-06 01:50:47 +00001023 // If we're instantiating a local function declaration, put the result
1024 // in the owner; otherwise we need to find the instantiated context.
1025 DeclContext *DC;
1026 if (D->getDeclContext()->isFunctionOrMethod())
1027 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001028 else if (isFriend && Qualifier) {
1029 CXXScopeSpec SS;
1030 SS.setScopeRep(Qualifier);
1031 SS.setRange(D->getQualifierRange());
1032 DC = SemaRef.computeDeclContext(SS);
1033 if (!DC) return 0;
1034 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001035 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1036 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001037 }
John McCall68b6b872010-02-06 01:50:47 +00001038
John McCall02cace72009-08-28 07:59:38 +00001039 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001040 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001041 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001042 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001043 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001044
John McCalld325daa2010-03-26 04:53:08 +00001045 if (Qualifier)
1046 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001047
John McCallb1a56e72010-03-26 23:10:15 +00001048 DeclContext *LexicalDC = Owner;
1049 if (!isFriend && D->isOutOfLine()) {
1050 assert(D->getDeclContext()->isFileContext());
1051 LexicalDC = D->getDeclContext();
1052 }
1053
1054 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregore53060f2009-06-25 22:08:12 +00001056 // Attach the parameters
1057 for (unsigned P = 0; P < Params.size(); ++P)
1058 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001059 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001060
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001061 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001062 if (TemplateParams) {
1063 // Our resulting instantiation is actually a function template, since we
1064 // are substituting only the outer template parameters. For example, given
1065 //
1066 // template<typename T>
1067 // struct X {
1068 // template<typename U> friend void f(T, U);
1069 // };
1070 //
1071 // X<int> x;
1072 //
1073 // We are instantiating the friend function template "f" within X<int>,
1074 // which means substituting int for T, but leaving "f" as a friend function
1075 // template.
1076 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001077 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001078 Function->getLocation(),
1079 Function->getDeclName(),
1080 TemplateParams, Function);
1081 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001082
1083 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001084
1085 if (isFriend && D->isThisDeclarationADefinition()) {
1086 // TODO: should we remember this connection regardless of whether
1087 // the friend declaration provided a body?
1088 FunctionTemplate->setInstantiatedFromMemberTemplate(
1089 D->getDescribedFunctionTemplate());
1090 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001091 } else if (FunctionTemplate) {
1092 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001093 std::pair<const TemplateArgument *, unsigned> Innermost
1094 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001095 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001096 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1097 Innermost.first,
1098 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001099 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001100 } else if (isFriend && D->isThisDeclarationADefinition()) {
1101 // TODO: should we remember this connection regardless of whether
1102 // the friend declaration provided a body?
1103 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001104 }
Douglas Gregora735b202009-10-13 14:39:41 +00001105
Douglas Gregore53060f2009-06-25 22:08:12 +00001106 if (InitFunctionInstantiation(Function, D))
1107 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Douglas Gregore53060f2009-06-25 22:08:12 +00001109 bool Redeclaration = false;
1110 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001111 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001112
John McCall68263142009-11-18 22:49:29 +00001113 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1114 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1115
John McCallaf2094e2010-04-08 09:05:18 +00001116 if (DependentFunctionTemplateSpecializationInfo *Info
1117 = D->getDependentSpecializationInfo()) {
1118 assert(isFriend && "non-friend has dependent specialization info?");
1119
1120 // This needs to be set now for future sanity.
1121 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1122
1123 // Instantiate the explicit template arguments.
1124 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1125 Info->getRAngleLoc());
1126 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1127 TemplateArgumentLoc Loc;
1128 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1129 return 0;
1130
1131 ExplicitArgs.addArgument(Loc);
1132 }
1133
1134 // Map the candidate templates to their instantiations.
1135 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1136 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1137 Info->getTemplate(I),
1138 TemplateArgs);
1139 if (!Temp) return 0;
1140
1141 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1142 }
1143
1144 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1145 &ExplicitArgs,
1146 Previous))
1147 Function->setInvalidDecl();
1148
1149 isExplicitSpecialization = true;
1150
1151 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001152 // Look only into the namespace where the friend would be declared to
1153 // find a previous declaration. This is the innermost enclosing namespace,
1154 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001155 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001156
Douglas Gregora735b202009-10-13 14:39:41 +00001157 // In C++, the previous declaration we find might be a tag type
1158 // (class or enum). In this case, the new declaration will hide the
1159 // tag type. Note that this does does not apply if we're declaring a
1160 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001161 if (Previous.isSingleTagDecl())
1162 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001163 }
1164
John McCall9f54ad42009-12-10 09:41:52 +00001165 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001166 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001167 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001168
John McCall76d32642010-04-24 01:30:58 +00001169 NamedDecl *PrincipalDecl = (TemplateParams
1170 ? cast<NamedDecl>(FunctionTemplate)
1171 : Function);
1172
Douglas Gregora735b202009-10-13 14:39:41 +00001173 // If the original function was part of a friend declaration,
1174 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001175 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001176 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001177 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001178 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001179 else
Douglas Gregora735b202009-10-13 14:39:41 +00001180 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001181
1182 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1183 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001184
1185 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1186 D->isThisDeclarationADefinition()) {
1187 // Check for a function body.
1188 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001189 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001190 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1191 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1192 << Function->getDeclName();
1193 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1194 Function->setInvalidDecl();
1195 }
1196 // Check for redefinitions due to other instantiations of this or
1197 // a similar friend function.
1198 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1199 REnd = Function->redecls_end();
1200 R != REnd; ++R) {
1201 if (*R != Function &&
1202 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1203 if (const FunctionDecl *RPattern
1204 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001205 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001206 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1207 << Function->getDeclName();
1208 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1209 Function->setInvalidDecl();
1210 break;
1211 }
1212 }
1213 }
1214 }
1215
Douglas Gregora735b202009-10-13 14:39:41 +00001216 }
1217
John McCall76d32642010-04-24 01:30:58 +00001218 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1219 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1220 PrincipalDecl->setNonMemberOperator();
1221
Douglas Gregore53060f2009-06-25 22:08:12 +00001222 return Function;
1223}
1224
Douglas Gregord60e1052009-08-27 16:57:43 +00001225Decl *
1226TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1227 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001228 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1229 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001230 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001231 // We are creating a function template specialization from a function
1232 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001233 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001234 llvm::FoldingSetNodeID ID;
Douglas Gregor24bae922010-07-08 18:37:38 +00001235 std::pair<const TemplateArgument *, unsigned> Innermost
1236 = TemplateArgs.getInnermost();
1237 FunctionTemplateSpecializationInfo::Profile(ID, Innermost.first,
1238 Innermost.second,
Douglas Gregor6b906862009-08-21 00:16:32 +00001239 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
1241 FunctionTemplateSpecializationInfo *Info
1242 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001243 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Douglas Gregor6b906862009-08-21 00:16:32 +00001245 // If we already have a function template specialization, return it.
1246 if (Info)
1247 return Info->Function;
1248 }
1249
John McCallb0cb0222010-03-27 05:57:59 +00001250 bool isFriend;
1251 if (FunctionTemplate)
1252 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1253 else
1254 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1255
Douglas Gregor79c22782010-01-16 20:21:20 +00001256 bool MergeWithParentScope = (TemplateParams != 0) ||
1257 !(isa<Decl>(Owner) &&
1258 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1259 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001260
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001261 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001262 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1263 TInfo = SubstFunctionType(D, Params);
1264 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001265 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001266 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001267
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001268 // \brief If the type of this function is not *directly* a function
1269 // type, then we're instantiating the a function that was declared
1270 // via a typedef, e.g.,
1271 //
1272 // typedef int functype(int, int);
1273 // functype func;
1274 //
1275 // In this case, we'll just go instantiate the ParmVarDecls that we
1276 // synthesized in the method declaration.
1277 if (!isa<FunctionProtoType>(T)) {
1278 assert(!Params.size() && "Instantiating type could not yield parameters");
1279 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1280 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1281 TemplateArgs);
1282 if (!P)
1283 return 0;
1284
1285 Params.push_back(P);
1286 }
1287 }
1288
John McCallb0cb0222010-03-27 05:57:59 +00001289 NestedNameSpecifier *Qualifier = D->getQualifier();
1290 if (Qualifier) {
1291 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1292 D->getQualifierRange(),
1293 TemplateArgs);
1294 if (!Qualifier) return 0;
1295 }
1296
1297 DeclContext *DC = Owner;
1298 if (isFriend) {
1299 if (Qualifier) {
1300 CXXScopeSpec SS;
1301 SS.setScopeRep(Qualifier);
1302 SS.setRange(D->getQualifierRange());
1303 DC = SemaRef.computeDeclContext(SS);
1304 } else {
1305 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1306 D->getDeclContext(),
1307 TemplateArgs);
1308 }
1309 if (!DC) return 0;
1310 }
1311
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001312 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001313 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001314 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Douglas Gregordec06662009-08-21 18:42:58 +00001316 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001317 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001318 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1319 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1320 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001321 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1322 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001323 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001324 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001325 Constructor->isInlineSpecified(),
1326 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001327 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1328 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1329 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1330 SemaRef.Context.getCanonicalType(ClassTy));
1331 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1332 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001333 T, Destructor->isInlineSpecified(),
1334 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001335 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001336 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001337 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001338 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001339 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1340 ConvTy);
1341 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1342 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001343 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001344 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001345 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001346 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001347 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001348 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001349 D->isStatic(),
1350 D->getStorageClassAsWritten(),
1351 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001352 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001353
John McCallb0cb0222010-03-27 05:57:59 +00001354 if (Qualifier)
1355 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001356
Douglas Gregord60e1052009-08-27 16:57:43 +00001357 if (TemplateParams) {
1358 // Our resulting instantiation is actually a function template, since we
1359 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001360 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001361 // template<typename T>
1362 // struct X {
1363 // template<typename U> void f(T, U);
1364 // };
1365 //
1366 // X<int> x;
1367 //
1368 // We are instantiating the member template "f" within X<int>, which means
1369 // substituting int for T, but leaving "f" as a member function template.
1370 // Build the function template itself.
1371 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1372 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001373 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001374 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001375 if (isFriend) {
1376 FunctionTemplate->setLexicalDeclContext(Owner);
1377 FunctionTemplate->setObjectOfFriendDecl(true);
1378 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001379 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001380 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001381 } else if (FunctionTemplate) {
1382 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001383 std::pair<const TemplateArgument *, unsigned> Innermost
1384 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001385 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001386 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1387 Innermost.first,
1388 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001389 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001390 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001391 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001392 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001393 }
1394
Mike Stump1eb44332009-09-09 15:08:12 +00001395 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001396 // out-of-line, the instantiation will have the same lexical
1397 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001398 if (isFriend) {
1399 Method->setLexicalDeclContext(Owner);
1400 Method->setObjectOfFriendDecl(true);
1401 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001402 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Douglas Gregor5545e162009-03-24 00:38:23 +00001404 // Attach the parameters
1405 for (unsigned P = 0; P < Params.size(); ++P)
1406 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001407 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001408
1409 if (InitMethodInstantiation(Method, D))
1410 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001411
John McCall68263142009-11-18 22:49:29 +00001412 LookupResult Previous(SemaRef, Name, SourceLocation(),
1413 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
John McCallb0cb0222010-03-27 05:57:59 +00001415 if (!FunctionTemplate || TemplateParams || isFriend) {
1416 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Douglas Gregordec06662009-08-21 18:42:58 +00001418 // In C++, the previous declaration we find might be a tag type
1419 // (class or enum). In this case, the new declaration will hide the
1420 // tag type. Note that this does does not apply if we're declaring a
1421 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001422 if (Previous.isSingleTagDecl())
1423 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001424 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001425
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001426 bool Redeclaration = false;
1427 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001428 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001429 /*FIXME:*/OverloadableAttrRequired);
1430
Douglas Gregor4ba31362009-12-01 17:24:26 +00001431 if (D->isPure())
1432 SemaRef.CheckPureMethod(Method, SourceRange());
1433
John McCall46460a62010-01-20 21:53:11 +00001434 Method->setAccess(D->getAccess());
1435
John McCallb0cb0222010-03-27 05:57:59 +00001436 if (FunctionTemplate) {
1437 // If there's a function template, let our caller handle it.
1438 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1439 // Don't hide a (potentially) valid declaration with an invalid one.
1440 } else {
1441 NamedDecl *DeclToAdd = (TemplateParams
1442 ? cast<NamedDecl>(FunctionTemplate)
1443 : Method);
1444 if (isFriend)
1445 Record->makeDeclVisibleInContext(DeclToAdd);
1446 else
1447 Owner->addDecl(DeclToAdd);
1448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001450 return Method;
1451}
1452
Douglas Gregor615c5d42009-03-24 16:43:20 +00001453Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001454 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001455}
1456
Douglas Gregor03b2b072009-03-24 00:15:49 +00001457Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001458 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001459}
1460
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001461Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001462 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001463}
1464
Douglas Gregor6477b692009-03-25 15:04:13 +00001465ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001466 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001467}
1468
John McCalle29ba202009-08-20 01:44:21 +00001469Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1470 TemplateTypeParmDecl *D) {
1471 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001472 const Type* T = D->getTypeForDecl();
1473 assert(T->isTemplateTypeParmType());
1474 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001475
John McCalle29ba202009-08-20 01:44:21 +00001476 TemplateTypeParmDecl *Inst =
1477 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001478 TTPT->getDepth() - 1, TTPT->getIndex(),
1479 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001480 D->wasDeclaredWithTypename(),
1481 D->isParameterPack());
1482
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001483 if (D->hasDefaultArgument())
1484 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001485
Douglas Gregor550d9b22009-10-31 17:21:17 +00001486 // Introduce this template parameter's instantiation into the instantiation
1487 // scope.
1488 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1489
John McCalle29ba202009-08-20 01:44:21 +00001490 return Inst;
1491}
1492
Douglas Gregor33642df2009-10-23 23:25:44 +00001493Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1494 NonTypeTemplateParmDecl *D) {
1495 // Substitute into the type of the non-type template parameter.
1496 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001497 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001498 if (DI) {
1499 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1500 D->getDeclName());
1501 if (DI) T = DI->getType();
1502 } else {
1503 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1504 D->getDeclName());
1505 DI = 0;
1506 }
1507 if (T.isNull())
1508 return 0;
1509
1510 // Check that this type is acceptable for a non-type template parameter.
1511 bool Invalid = false;
1512 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1513 if (T.isNull()) {
1514 T = SemaRef.Context.IntTy;
1515 Invalid = true;
1516 }
1517
1518 NonTypeTemplateParmDecl *Param
1519 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1520 D->getDepth() - 1, D->getPosition(),
1521 D->getIdentifier(), T, DI);
1522 if (Invalid)
1523 Param->setInvalidDecl();
1524
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001525 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001526
1527 // Introduce this template parameter's instantiation into the instantiation
1528 // scope.
1529 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001530 return Param;
1531}
1532
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001533Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001534TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1535 TemplateTemplateParmDecl *D) {
1536 // Instantiate the template parameter list of the template template parameter.
1537 TemplateParameterList *TempParams = D->getTemplateParameters();
1538 TemplateParameterList *InstParams;
1539 {
1540 // Perform the actual substitution of template parameters within a new,
1541 // local instantiation scope.
1542 Sema::LocalInstantiationScope Scope(SemaRef);
1543 InstParams = SubstTemplateParams(TempParams);
1544 if (!InstParams)
1545 return NULL;
1546 }
1547
1548 // Build the template template parameter.
1549 TemplateTemplateParmDecl *Param
1550 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1551 D->getDepth() - 1, D->getPosition(),
1552 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001553 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001554
Douglas Gregor9106ef72009-11-11 16:58:32 +00001555 // Introduce this template parameter's instantiation into the instantiation
1556 // scope.
1557 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1558
1559 return Param;
1560}
1561
Douglas Gregor48c32a72009-11-17 06:07:40 +00001562Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1563 // Using directives are never dependent, so they require no explicit
1564
1565 UsingDirectiveDecl *Inst
1566 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1567 D->getNamespaceKeyLocation(),
1568 D->getQualifierRange(), D->getQualifier(),
1569 D->getIdentLocation(),
1570 D->getNominatedNamespace(),
1571 D->getCommonAncestor());
1572 Owner->addDecl(Inst);
1573 return Inst;
1574}
1575
John McCalled976492009-12-04 22:46:56 +00001576Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1577 // The nested name specifier is non-dependent, so no transformation
1578 // is required.
1579
John McCall9f54ad42009-12-10 09:41:52 +00001580 // We only need to do redeclaration lookups if we're in a class
1581 // scope (in fact, it's not really even possible in non-class
1582 // scopes).
1583 bool CheckRedeclaration = Owner->isRecord();
1584
1585 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1586 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1587
John McCalled976492009-12-04 22:46:56 +00001588 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1589 D->getLocation(),
1590 D->getNestedNameRange(),
1591 D->getUsingLocation(),
1592 D->getTargetNestedNameDecl(),
1593 D->getDeclName(),
1594 D->isTypeName());
1595
1596 CXXScopeSpec SS;
1597 SS.setScopeRep(D->getTargetNestedNameDecl());
1598 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001599
1600 if (CheckRedeclaration) {
1601 Prev.setHideTags(false);
1602 SemaRef.LookupQualifiedName(Prev, Owner);
1603
1604 // Check for invalid redeclarations.
1605 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1606 D->isTypeName(), SS,
1607 D->getLocation(), Prev))
1608 NewUD->setInvalidDecl();
1609
1610 }
1611
1612 if (!NewUD->isInvalidDecl() &&
1613 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001614 D->getLocation()))
1615 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001616
John McCalled976492009-12-04 22:46:56 +00001617 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1618 NewUD->setAccess(D->getAccess());
1619 Owner->addDecl(NewUD);
1620
John McCall9f54ad42009-12-10 09:41:52 +00001621 // Don't process the shadow decls for an invalid decl.
1622 if (NewUD->isInvalidDecl())
1623 return NewUD;
1624
John McCall323c3102009-12-22 22:26:37 +00001625 bool isFunctionScope = Owner->isFunctionOrMethod();
1626
John McCall9f54ad42009-12-10 09:41:52 +00001627 // Process the shadow decls.
1628 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1629 I != E; ++I) {
1630 UsingShadowDecl *Shadow = *I;
1631 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001632 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1633 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001634 TemplateArgs));
1635
1636 if (CheckRedeclaration &&
1637 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1638 continue;
1639
1640 UsingShadowDecl *InstShadow
1641 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1642 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001643
1644 if (isFunctionScope)
1645 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001646 }
John McCalled976492009-12-04 22:46:56 +00001647
1648 return NewUD;
1649}
1650
1651Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001652 // Ignore these; we handle them in bulk when processing the UsingDecl.
1653 return 0;
John McCalled976492009-12-04 22:46:56 +00001654}
1655
John McCall7ba107a2009-11-18 02:36:19 +00001656Decl * TemplateDeclInstantiator
1657 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001658 NestedNameSpecifier *NNS =
1659 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1660 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001661 TemplateArgs);
1662 if (!NNS)
1663 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001665 CXXScopeSpec SS;
1666 SS.setRange(D->getTargetNestedNameRange());
1667 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
1669 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001670 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001671 D->getUsingLoc(), SS, D->getLocation(),
1672 D->getDeclName(), 0,
1673 /*instantiation*/ true,
1674 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001675 if (UD)
John McCalled976492009-12-04 22:46:56 +00001676 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1677
John McCall7ba107a2009-11-18 02:36:19 +00001678 return UD;
1679}
1680
1681Decl * TemplateDeclInstantiator
1682 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1683 NestedNameSpecifier *NNS =
1684 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1685 D->getTargetNestedNameRange(),
1686 TemplateArgs);
1687 if (!NNS)
1688 return 0;
1689
1690 CXXScopeSpec SS;
1691 SS.setRange(D->getTargetNestedNameRange());
1692 SS.setScopeRep(NNS);
1693
1694 NamedDecl *UD =
1695 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1696 D->getUsingLoc(), SS, D->getLocation(),
1697 D->getDeclName(), 0,
1698 /*instantiation*/ true,
1699 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001700 if (UD)
John McCalled976492009-12-04 22:46:56 +00001701 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1702
Anders Carlsson0d8df782009-08-29 19:37:28 +00001703 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001704}
1705
John McCallce3ff2b2009-08-25 22:02:44 +00001706Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001707 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001708 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001709 if (D->isInvalidDecl())
1710 return 0;
1711
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001712 return Instantiator.Visit(D);
1713}
1714
John McCalle29ba202009-08-20 01:44:21 +00001715/// \brief Instantiates a nested template parameter list in the current
1716/// instantiation context.
1717///
1718/// \param L The parameter list to instantiate
1719///
1720/// \returns NULL if there was an error
1721TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001722TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001723 // Get errors for all the parameters before bailing out.
1724 bool Invalid = false;
1725
1726 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001727 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001728 ParamVector Params;
1729 Params.reserve(N);
1730 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1731 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001732 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001733 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001734 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001735 }
1736
1737 // Clean up if we had an error.
1738 if (Invalid) {
1739 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1740 PI != PE; ++PI)
1741 if (*PI)
1742 (*PI)->Destroy(SemaRef.Context);
1743 return NULL;
1744 }
1745
1746 TemplateParameterList *InstL
1747 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1748 L->getLAngleLoc(), &Params.front(), N,
1749 L->getRAngleLoc());
1750 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001751}
John McCalle29ba202009-08-20 01:44:21 +00001752
Douglas Gregored9c0f92009-10-29 00:04:11 +00001753/// \brief Instantiate the declaration of a class template partial
1754/// specialization.
1755///
1756/// \param ClassTemplate the (instantiated) class template that is partially
1757// specialized by the instantiation of \p PartialSpec.
1758///
1759/// \param PartialSpec the (uninstantiated) class template partial
1760/// specialization that we are instantiating.
1761///
1762/// \returns true if there was an error, false otherwise.
1763bool
1764TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1765 ClassTemplateDecl *ClassTemplate,
1766 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001767 // Create a local instantiation scope for this class template partial
1768 // specialization, which will contain the instantiations of the template
1769 // parameters.
1770 Sema::LocalInstantiationScope Scope(SemaRef);
1771
Douglas Gregored9c0f92009-10-29 00:04:11 +00001772 // Substitute into the template parameters of the class template partial
1773 // specialization.
1774 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1775 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1776 if (!InstParams)
1777 return true;
1778
1779 // Substitute into the template arguments of the class template partial
1780 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001781 const TemplateArgumentLoc *PartialSpecTemplateArgs
1782 = PartialSpec->getTemplateArgsAsWritten();
1783 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1784
John McCalld5532b62009-11-23 01:53:49 +00001785 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001786 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001787 TemplateArgumentLoc Loc;
1788 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001789 return true;
John McCalld5532b62009-11-23 01:53:49 +00001790 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001791 }
1792
1793
1794 // Check that the template argument list is well-formed for this
1795 // class template.
1796 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1797 InstTemplateArgs.size());
1798 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1799 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001800 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001801 false,
1802 Converted))
1803 return true;
1804
1805 // Figure out where to insert this class template partial specialization
1806 // in the member template's set of class template partial specializations.
1807 llvm::FoldingSetNodeID ID;
1808 ClassTemplatePartialSpecializationDecl::Profile(ID,
1809 Converted.getFlatArguments(),
1810 Converted.flatSize(),
1811 SemaRef.Context);
1812 void *InsertPos = 0;
1813 ClassTemplateSpecializationDecl *PrevDecl
1814 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1815 InsertPos);
1816
1817 // Build the canonical type that describes the converted template
1818 // arguments of the class template partial specialization.
1819 QualType CanonType
1820 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1821 Converted.getFlatArguments(),
1822 Converted.flatSize());
1823
1824 // Build the fully-sugared type for this class template
1825 // specialization as the user wrote in the specialization
1826 // itself. This means that we'll pretty-print the type retrieved
1827 // from the specialization's declaration the way that the user
1828 // actually wrote the specialization, rather than formatting the
1829 // name based on the "canonical" representation used to store the
1830 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001831 TypeSourceInfo *WrittenTy
1832 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1833 TemplateName(ClassTemplate),
1834 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001835 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001836 CanonType);
1837
1838 if (PrevDecl) {
1839 // We've already seen a partial specialization with the same template
1840 // parameters and template arguments. This can happen, for example, when
1841 // substituting the outer template arguments ends up causing two
1842 // class template partial specializations of a member class template
1843 // to have identical forms, e.g.,
1844 //
1845 // template<typename T, typename U>
1846 // struct Outer {
1847 // template<typename X, typename Y> struct Inner;
1848 // template<typename Y> struct Inner<T, Y>;
1849 // template<typename Y> struct Inner<U, Y>;
1850 // };
1851 //
1852 // Outer<int, int> outer; // error: the partial specializations of Inner
1853 // // have the same signature.
1854 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1855 << WrittenTy;
1856 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1857 << SemaRef.Context.getTypeDeclType(PrevDecl);
1858 return true;
1859 }
1860
1861
1862 // Create the class template partial specialization declaration.
1863 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001864 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1865 PartialSpec->getTagKind(),
1866 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001867 PartialSpec->getLocation(),
1868 InstParams,
1869 ClassTemplate,
1870 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001871 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001872 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001873 0,
1874 ClassTemplate->getPartialSpecializations().size());
John McCallb6217662010-03-15 10:12:16 +00001875 // Substitute the nested name specifier, if any.
1876 if (SubstQualifier(PartialSpec, InstPartialSpec))
1877 return 0;
1878
Douglas Gregored9c0f92009-10-29 00:04:11 +00001879 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001880 InstPartialSpec->setTypeAsWritten(WrittenTy);
1881
Douglas Gregored9c0f92009-10-29 00:04:11 +00001882 // Add this partial specialization to the set of class template partial
1883 // specializations.
1884 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1885 InsertPos);
1886 return false;
1887}
1888
John McCall21ef0fa2010-03-11 09:03:00 +00001889TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001890TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001891 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001892 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1893 assert(OldTInfo && "substituting function without type source info");
1894 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001895 TypeSourceInfo *NewTInfo
1896 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1897 D->getTypeSpecStartLoc(),
1898 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001899 if (!NewTInfo)
1900 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001901
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001902 if (NewTInfo != OldTInfo) {
1903 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001904 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001905 if (FunctionProtoTypeLoc *OldProtoLoc
1906 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1907 TypeLoc NewTL = NewTInfo->getTypeLoc();
1908 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1909 assert(NewProtoLoc && "Missing prototype?");
1910 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1911 // FIXME: Variadic templates will break this.
1912 Params.push_back(NewProtoLoc->getArg(i));
1913 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001914 OldProtoLoc->getArg(i),
1915 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001916 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001917 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001918 } else {
1919 // The function type itself was not dependent and therefore no
1920 // substitution occurred. However, we still need to instantiate
1921 // the function parameters themselves.
1922 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001923 if (FunctionProtoTypeLoc *OldProtoLoc
1924 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1925 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1926 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1927 if (!Parm)
1928 return 0;
1929 Params.push_back(Parm);
1930 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001931 }
1932 }
John McCall21ef0fa2010-03-11 09:03:00 +00001933 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001934}
1935
Mike Stump1eb44332009-09-09 15:08:12 +00001936/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001937/// declaration (New) from the corresponding fields of its template (Tmpl).
1938///
1939/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001940bool
1941TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001942 FunctionDecl *Tmpl) {
1943 if (Tmpl->isDeleted())
1944 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Douglas Gregorcca9e962009-07-01 22:01:06 +00001946 // If we are performing substituting explicitly-specified template arguments
1947 // or deduced template arguments into a function template and we reach this
1948 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001949 // to keeping the new function template specialization. We therefore
1950 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001951 // into a template instantiation for this specific function template
1952 // specialization, which is not a SFINAE context, so that we diagnose any
1953 // further errors in the declaration itself.
1954 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1955 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1956 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1957 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001958 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001959 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001960 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001961 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001962 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001963 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1964 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001965 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001966 }
1967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001969 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1970 assert(Proto && "Function template without prototype?");
1971
1972 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1973 Proto->getNoReturnAttr()) {
1974 // The function has an exception specification or a "noreturn"
1975 // attribute. Substitute into each of the exception types.
1976 llvm::SmallVector<QualType, 4> Exceptions;
1977 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1978 // FIXME: Poor location information!
1979 QualType T
1980 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1981 New->getLocation(), New->getDeclName());
1982 if (T.isNull() ||
1983 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1984 continue;
1985
1986 Exceptions.push_back(T);
1987 }
1988
1989 // Rebuild the function type
1990
1991 const FunctionProtoType *NewProto
1992 = New->getType()->getAs<FunctionProtoType>();
1993 assert(NewProto && "Template instantiation without function prototype?");
1994 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1995 NewProto->arg_type_begin(),
1996 NewProto->getNumArgs(),
1997 NewProto->isVariadic(),
1998 NewProto->getTypeQuals(),
1999 Proto->hasExceptionSpec(),
2000 Proto->hasAnyExceptionSpec(),
2001 Exceptions.size(),
2002 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002003 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002004 }
2005
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002006 InstantiateAttrs(Tmpl, New);
2007
Douglas Gregore53060f2009-06-25 22:08:12 +00002008 return false;
2009}
2010
Douglas Gregor5545e162009-03-24 00:38:23 +00002011/// \brief Initializes common fields of an instantiated method
2012/// declaration (New) from the corresponding fields of its template
2013/// (Tmpl).
2014///
2015/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002016bool
2017TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002018 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002019 if (InitFunctionInstantiation(New, Tmpl))
2020 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor5545e162009-03-24 00:38:23 +00002022 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
2023 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002024 if (Tmpl->isVirtualAsWritten())
2025 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00002026
2027 // FIXME: attributes
2028 // FIXME: New needs a pointer to Tmpl
2029 return false;
2030}
Douglas Gregora58861f2009-05-13 20:28:22 +00002031
2032/// \brief Instantiate the definition of the given function from its
2033/// template.
2034///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002035/// \param PointOfInstantiation the point at which the instantiation was
2036/// required. Note that this is not precisely a "point of instantiation"
2037/// for the function, but it's close.
2038///
Douglas Gregora58861f2009-05-13 20:28:22 +00002039/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002040/// function template specialization or member function of a class template
2041/// specialization.
2042///
2043/// \param Recursive if true, recursively instantiates any functions that
2044/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002045///
2046/// \param DefinitionRequired if true, then we are performing an explicit
2047/// instantiation where the body of the function is required. Complain if
2048/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002049void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002050 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002051 bool Recursive,
2052 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002053 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002054 return;
2055
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002056 // Never instantiate an explicit specialization.
2057 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2058 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002059
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002060 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002061 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002062 Stmt *Pattern = 0;
2063 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002064 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002065
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002066 if (!Pattern) {
2067 if (DefinitionRequired) {
2068 if (Function->getPrimaryTemplate())
2069 Diag(PointOfInstantiation,
2070 diag::err_explicit_instantiation_undefined_func_template)
2071 << Function->getPrimaryTemplate();
2072 else
2073 Diag(PointOfInstantiation,
2074 diag::err_explicit_instantiation_undefined_member)
2075 << 1 << Function->getDeclName() << Function->getDeclContext();
2076
2077 if (PatternDecl)
2078 Diag(PatternDecl->getLocation(),
2079 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002080 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002081 }
2082
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002083 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002084 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002085
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002086 // C++0x [temp.explicit]p9:
2087 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002088 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002089 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002090 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002091 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002092 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002093 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002095 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2096 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002097 return;
2098
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002099 // If we're performing recursive template instantiation, create our own
2100 // queue of pending implicit instantiations that we will instantiate later,
2101 // while we're still within our own instantiation context.
2102 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2103 if (Recursive)
2104 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Douglas Gregor9679caf2010-05-12 17:27:19 +00002106 EnterExpressionEvaluationContext EvalContext(*this,
2107 Action::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002108 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2109
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002110 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002111 // recorded, unless we're actually a member function within a local
2112 // class, in which case we need to merge our results with the parent
2113 // scope (of the enclosing function).
2114 bool MergeWithParentScope = false;
2115 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2116 MergeWithParentScope = Rec->isLocalClass();
2117
2118 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002120 // Introduce the instantiated function parameters into the local
2121 // instantiation scope.
2122 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2123 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2124 Function->getParamDecl(I));
2125
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002126 // Enter the scope of this instantiation. We don't use
2127 // PushDeclContext because we don't have a scope.
2128 DeclContext *PreviousContext = CurContext;
2129 CurContext = Function;
2130
Mike Stump1eb44332009-09-09 15:08:12 +00002131 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002132 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002133
2134 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002135 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002136 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2137 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2138 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002139 }
2140
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002141 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002142 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002143
Douglas Gregor52604ab2009-09-11 21:19:12 +00002144 if (Body.isInvalid())
2145 Function->setInvalidDecl();
2146
Mike Stump1eb44332009-09-09 15:08:12 +00002147 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002148 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002149
John McCall0c01d182010-03-24 05:22:00 +00002150 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2151
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002152 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002153
2154 DeclGroupRef DG(Function);
2155 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregor60406be2010-01-16 22:29:39 +00002157 // This class may have local implicit instantiations that need to be
2158 // instantiation within this scope.
2159 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2160 Scope.Exit();
2161
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002162 if (Recursive) {
2163 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002164 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002165 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002167 // Restore the set of pending implicit instantiations.
2168 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2169 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002170}
2171
2172/// \brief Instantiate the definition of the given variable from its
2173/// template.
2174///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002175/// \param PointOfInstantiation the point at which the instantiation was
2176/// required. Note that this is not precisely a "point of instantiation"
2177/// for the function, but it's close.
2178///
2179/// \param Var the already-instantiated declaration of a static member
2180/// variable of a class template specialization.
2181///
2182/// \param Recursive if true, recursively instantiates any functions that
2183/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002184///
2185/// \param DefinitionRequired if true, then we are performing an explicit
2186/// instantiation where an out-of-line definition of the member variable
2187/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002188void Sema::InstantiateStaticDataMemberDefinition(
2189 SourceLocation PointOfInstantiation,
2190 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002191 bool Recursive,
2192 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002193 if (Var->isInvalidDecl())
2194 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Douglas Gregor7caa6822009-07-24 20:34:43 +00002196 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002197 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002198 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002199 assert(Def->isStaticDataMember() && "Not a static data member?");
2200 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Douglas Gregor0d035142009-10-27 18:42:08 +00002202 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002203 // We did not find an out-of-line definition of this static data member,
2204 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002205 // instantiate this definition (or provide a specialization for it) in
2206 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002207 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002208 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002209 Diag(PointOfInstantiation,
2210 diag::err_explicit_instantiation_undefined_member)
2211 << 2 << Var->getDeclName() << Var->getDeclContext();
2212 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2213 }
2214
Douglas Gregor7caa6822009-07-24 20:34:43 +00002215 return;
2216 }
2217
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002218 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002219 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002220 return;
2221
2222 // C++0x [temp.explicit]p9:
2223 // Except for inline functions, other explicit instantiation declarations
2224 // have the effect of suppressing the implicit instantiation of the entity
2225 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002226 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002227 == TSK_ExplicitInstantiationDeclaration)
2228 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregor7caa6822009-07-24 20:34:43 +00002230 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2231 if (Inst)
2232 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregor7caa6822009-07-24 20:34:43 +00002234 // If we're performing recursive template instantiation, create our own
2235 // queue of pending implicit instantiations that we will instantiate later,
2236 // while we're still within our own instantiation context.
2237 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2238 if (Recursive)
2239 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Douglas Gregor7caa6822009-07-24 20:34:43 +00002241 // Enter the scope of this instantiation. We don't use
2242 // PushDeclContext because we don't have a scope.
2243 DeclContext *PreviousContext = CurContext;
2244 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002246 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002247 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002248 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002249 CurContext = PreviousContext;
2250
2251 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002252 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2253 assert(MSInfo && "Missing member specialization information?");
2254 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2255 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002256 DeclGroupRef DG(Var);
2257 Consumer.HandleTopLevelDecl(DG);
2258 }
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Douglas Gregor7caa6822009-07-24 20:34:43 +00002260 if (Recursive) {
2261 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002262 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002263 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Douglas Gregor7caa6822009-07-24 20:34:43 +00002265 // Restore the set of pending implicit instantiations.
2266 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002267 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002268}
Douglas Gregor815215d2009-05-27 05:35:12 +00002269
Anders Carlsson09025312009-08-29 05:16:22 +00002270void
2271Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2272 const CXXConstructorDecl *Tmpl,
2273 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Anders Carlsson09025312009-08-29 05:16:22 +00002275 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002276 bool AnyErrors = false;
2277
Anders Carlsson09025312009-08-29 05:16:22 +00002278 // Instantiate all the initializers.
2279 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002280 InitsEnd = Tmpl->init_end();
2281 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002282 CXXBaseOrMemberInitializer *Init = *Inits;
2283
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002284 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002285 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002286 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002288 // Instantiate the initializer.
2289 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2290 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2291 AnyErrors = true;
2292 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002293 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002294
Anders Carlsson09025312009-08-29 05:16:22 +00002295 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002296 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002297 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002298 TemplateArgs,
2299 Init->getSourceLocation(),
2300 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002301 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002302 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002303 New->setInvalidDecl();
2304 continue;
2305 }
2306
John McCalla93c9342009-12-07 02:54:59 +00002307 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002308 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002309 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002310 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002311 Init->getRParenLoc(),
2312 New->getParent());
2313 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002314 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002316 // Is this an anonymous union?
2317 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002318 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2319 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002320 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002321 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2322 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002323 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002324
2325 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002326 NewArgs.size(),
2327 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002328 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002329 Init->getRParenLoc());
2330 }
2331
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002332 if (NewInit.isInvalid()) {
2333 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002334 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002335 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002336 // FIXME: It would be nice if ASTOwningVector had a release function.
2337 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Anders Carlsson09025312009-08-29 05:16:22 +00002339 NewInits.push_back((MemInitTy *)NewInit.get());
2340 }
2341 }
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Anders Carlsson09025312009-08-29 05:16:22 +00002343 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002344 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002345 /*FIXME: ColonLoc */
2346 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 NewInits.data(), NewInits.size(),
2348 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002349}
2350
John McCall52a575a2009-08-29 08:11:13 +00002351// TODO: this could be templated if the various decl types used the
2352// same method name.
2353static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2354 ClassTemplateDecl *Instance) {
2355 Pattern = Pattern->getCanonicalDecl();
2356
2357 do {
2358 Instance = Instance->getCanonicalDecl();
2359 if (Pattern == Instance) return true;
2360 Instance = Instance->getInstantiatedFromMemberTemplate();
2361 } while (Instance);
2362
2363 return false;
2364}
2365
Douglas Gregor0d696532009-09-28 06:34:35 +00002366static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2367 FunctionTemplateDecl *Instance) {
2368 Pattern = Pattern->getCanonicalDecl();
2369
2370 do {
2371 Instance = Instance->getCanonicalDecl();
2372 if (Pattern == Instance) return true;
2373 Instance = Instance->getInstantiatedFromMemberTemplate();
2374 } while (Instance);
2375
2376 return false;
2377}
2378
Douglas Gregored9c0f92009-10-29 00:04:11 +00002379static bool
2380isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2381 ClassTemplatePartialSpecializationDecl *Instance) {
2382 Pattern
2383 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2384 do {
2385 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2386 Instance->getCanonicalDecl());
2387 if (Pattern == Instance)
2388 return true;
2389 Instance = Instance->getInstantiatedFromMember();
2390 } while (Instance);
2391
2392 return false;
2393}
2394
John McCall52a575a2009-08-29 08:11:13 +00002395static bool isInstantiationOf(CXXRecordDecl *Pattern,
2396 CXXRecordDecl *Instance) {
2397 Pattern = Pattern->getCanonicalDecl();
2398
2399 do {
2400 Instance = Instance->getCanonicalDecl();
2401 if (Pattern == Instance) return true;
2402 Instance = Instance->getInstantiatedFromMemberClass();
2403 } while (Instance);
2404
2405 return false;
2406}
2407
2408static bool isInstantiationOf(FunctionDecl *Pattern,
2409 FunctionDecl *Instance) {
2410 Pattern = Pattern->getCanonicalDecl();
2411
2412 do {
2413 Instance = Instance->getCanonicalDecl();
2414 if (Pattern == Instance) return true;
2415 Instance = Instance->getInstantiatedFromMemberFunction();
2416 } while (Instance);
2417
2418 return false;
2419}
2420
2421static bool isInstantiationOf(EnumDecl *Pattern,
2422 EnumDecl *Instance) {
2423 Pattern = Pattern->getCanonicalDecl();
2424
2425 do {
2426 Instance = Instance->getCanonicalDecl();
2427 if (Pattern == Instance) return true;
2428 Instance = Instance->getInstantiatedFromMemberEnum();
2429 } while (Instance);
2430
2431 return false;
2432}
2433
John McCalled976492009-12-04 22:46:56 +00002434static bool isInstantiationOf(UsingShadowDecl *Pattern,
2435 UsingShadowDecl *Instance,
2436 ASTContext &C) {
2437 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2438}
2439
2440static bool isInstantiationOf(UsingDecl *Pattern,
2441 UsingDecl *Instance,
2442 ASTContext &C) {
2443 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2444}
2445
John McCall7ba107a2009-11-18 02:36:19 +00002446static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2447 UsingDecl *Instance,
2448 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002449 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002450}
2451
2452static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002453 UsingDecl *Instance,
2454 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002455 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002456}
2457
John McCall52a575a2009-08-29 08:11:13 +00002458static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2459 VarDecl *Instance) {
2460 assert(Instance->isStaticDataMember());
2461
2462 Pattern = Pattern->getCanonicalDecl();
2463
2464 do {
2465 Instance = Instance->getCanonicalDecl();
2466 if (Pattern == Instance) return true;
2467 Instance = Instance->getInstantiatedFromStaticDataMember();
2468 } while (Instance);
2469
2470 return false;
2471}
2472
John McCalled976492009-12-04 22:46:56 +00002473// Other is the prospective instantiation
2474// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002475static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002476 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002477 if (UnresolvedUsingTypenameDecl *UUD
2478 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2479 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2480 return isInstantiationOf(UUD, UD, Ctx);
2481 }
2482 }
2483
2484 if (UnresolvedUsingValueDecl *UUD
2485 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002486 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2487 return isInstantiationOf(UUD, UD, Ctx);
2488 }
2489 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002490
Anders Carlsson0d8df782009-08-29 19:37:28 +00002491 return false;
2492 }
Mike Stump1eb44332009-09-09 15:08:12 +00002493
John McCall52a575a2009-08-29 08:11:13 +00002494 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2495 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002496
John McCall52a575a2009-08-29 08:11:13 +00002497 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2498 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002499
John McCall52a575a2009-08-29 08:11:13 +00002500 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2501 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002502
Douglas Gregor7caa6822009-07-24 20:34:43 +00002503 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002504 if (Var->isStaticDataMember())
2505 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2506
2507 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2508 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002509
Douglas Gregor0d696532009-09-28 06:34:35 +00002510 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2511 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2512
Douglas Gregored9c0f92009-10-29 00:04:11 +00002513 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2514 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2515 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2516 PartialSpec);
2517
Anders Carlssond8b285f2009-09-01 04:26:58 +00002518 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2519 if (!Field->getDeclName()) {
2520 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002521 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002522 cast<FieldDecl>(D);
2523 }
2524 }
Mike Stump1eb44332009-09-09 15:08:12 +00002525
John McCalled976492009-12-04 22:46:56 +00002526 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2527 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2528
2529 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2530 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2531
Douglas Gregor815215d2009-05-27 05:35:12 +00002532 return D->getDeclName() && isa<NamedDecl>(Other) &&
2533 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2534}
2535
2536template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002537static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002538 NamedDecl *D,
2539 ForwardIterator first,
2540 ForwardIterator last) {
2541 for (; first != last; ++first)
2542 if (isInstantiationOf(Ctx, D, *first))
2543 return cast<NamedDecl>(*first);
2544
2545 return 0;
2546}
2547
John McCall02cace72009-08-28 07:59:38 +00002548/// \brief Finds the instantiation of the given declaration context
2549/// within the current instantiation.
2550///
2551/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002552DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002553 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002554 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002555 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002556 return cast_or_null<DeclContext>(ID);
2557 } else return DC;
2558}
2559
Douglas Gregored961e72009-05-27 17:54:46 +00002560/// \brief Find the instantiation of the given declaration within the
2561/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002562///
2563/// This routine is intended to be used when \p D is a declaration
2564/// referenced from within a template, that needs to mapped into the
2565/// corresponding declaration within an instantiation. For example,
2566/// given:
2567///
2568/// \code
2569/// template<typename T>
2570/// struct X {
2571/// enum Kind {
2572/// KnownValue = sizeof(T)
2573/// };
2574///
2575/// bool getKind() const { return KnownValue; }
2576/// };
2577///
2578/// template struct X<int>;
2579/// \endcode
2580///
2581/// In the instantiation of X<int>::getKind(), we need to map the
2582/// EnumConstantDecl for KnownValue (which refers to
2583/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002584/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2585/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002586NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002587 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002588 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002589 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002590 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002591 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002592 // D is a local of some kind. Look into the map of local
2593 // declarations to their instantiations.
2594 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2595 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002596
Douglas Gregore95b4092009-09-16 18:34:49 +00002597 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2598 if (!Record->isDependentContext())
2599 return D;
2600
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002601 // If the RecordDecl is actually the injected-class-name or a
2602 // "templated" declaration for a class template, class template
2603 // partial specialization, or a member class of a class template,
2604 // substitute into the injected-class-name of the class template
2605 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002606 QualType T;
2607 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2608
2609 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002610 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002611 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2612 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002613 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002614
2615 // If we call SubstType with an InjectedClassNameType here we
2616 // can end up in an infinite loop.
2617 T = Context.getTypeDeclType(Record);
2618 assert(isa<InjectedClassNameType>(T) &&
2619 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002620 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002621 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002622
2623 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002624 // Substitute into the injected-class-name to get the type
2625 // corresponding to the instantiation we want, which may also be
2626 // the current instantiation (if we're in a template
2627 // definition). This substitution should never fail, since we
2628 // know we can instantiate the injected-class-name or we
2629 // wouldn't have gotten to the injected-class-name!
2630
2631 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2632 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002633 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2634 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2635
2636 if (!T->isDependentType()) {
2637 assert(T->isRecordType() && "Instantiation must produce a record type");
2638 return T->getAs<RecordType>()->getDecl();
2639 }
2640
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002641 // We are performing "partial" template instantiation to create
2642 // the member declarations for the members of a class template
2643 // specialization. Therefore, D is actually referring to something
2644 // in the current instantiation. Look through the current
2645 // context, which contains actual instantiations, to find the
2646 // instantiation of the "current instantiation" that D refers
2647 // to.
2648 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002649 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002650 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002651 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002652 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002653 if (isInstantiationOf(ClassTemplate,
2654 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002655 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002656
2657 if (!DC->isDependentContext())
2658 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002659 }
2660
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002661 // We're performing "instantiation" of a member of the current
2662 // instantiation while we are type-checking the
2663 // definition. Compute the declaration context and return that.
2664 assert(!SawNonDependentContext &&
2665 "No dependent context while instantiating record");
2666 DeclContext *DC = computeDeclContext(T);
2667 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002668 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002669 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002670 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002671
Douglas Gregore95b4092009-09-16 18:34:49 +00002672 // Fall through to deal with other dependent record types (e.g.,
2673 // anonymous unions in class templates).
2674 }
John McCall52a575a2009-08-29 08:11:13 +00002675
Douglas Gregore95b4092009-09-16 18:34:49 +00002676 if (!ParentDC->isDependentContext())
2677 return D;
2678
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002679 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002680 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002681 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Douglas Gregor815215d2009-05-27 05:35:12 +00002683 if (ParentDC != D->getDeclContext()) {
2684 // We performed some kind of instantiation in the parent context,
2685 // so now we need to look into the instantiated parent context to
2686 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002687
John McCall3cb0ebd2010-03-10 03:28:59 +00002688 // If our context used to be dependent, we may need to instantiate
2689 // it before performing lookup into that context.
2690 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002691 if (!Spec->isDependentContext()) {
2692 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002693 const RecordType *Tag = T->getAs<RecordType>();
2694 assert(Tag && "type of non-dependent record is not a RecordType");
2695 if (!Tag->isBeingDefined() &&
2696 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2697 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002698 }
2699 }
2700
Douglas Gregor815215d2009-05-27 05:35:12 +00002701 NamedDecl *Result = 0;
2702 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002703 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002704 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2705 } else {
2706 // Since we don't have a name for the entity we're looking for,
2707 // our only option is to walk through all of the declarations to
2708 // find that name. This will occur in a few cases:
2709 //
2710 // - anonymous struct/union within a template
2711 // - unnamed class/struct/union/enum within a template
2712 //
2713 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002714 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002715 ParentDC->decls_begin(),
2716 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
John McCall9f54ad42009-12-10 09:41:52 +00002719 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002720 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2721 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002722 && "Unable to find instantiation of declaration!");
2723
Douglas Gregor815215d2009-05-27 05:35:12 +00002724 D = Result;
2725 }
2726
Douglas Gregor815215d2009-05-27 05:35:12 +00002727 return D;
2728}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002729
Mike Stump1eb44332009-09-09 15:08:12 +00002730/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002731/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002732void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2733 while (!PendingLocalImplicitInstantiations.empty() ||
2734 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2735 PendingImplicitInstantiation Inst;
2736
2737 if (PendingLocalImplicitInstantiations.empty()) {
2738 Inst = PendingImplicitInstantiations.front();
2739 PendingImplicitInstantiations.pop_front();
2740 } else {
2741 Inst = PendingLocalImplicitInstantiations.front();
2742 PendingLocalImplicitInstantiations.pop_front();
2743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Douglas Gregor7caa6822009-07-24 20:34:43 +00002745 // Instantiate function definitions
2746 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002747 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002748 Function->getLocation(), *this,
2749 Context.getSourceManager(),
2750 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002752 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002753 continue;
2754 }
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Douglas Gregor7caa6822009-07-24 20:34:43 +00002756 // Instantiate static data member definitions.
2757 VarDecl *Var = cast<VarDecl>(Inst.first);
2758 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002759
Chandler Carruth291b4412010-02-13 10:17:50 +00002760 // Don't try to instantiate declarations if the most recent redeclaration
2761 // is invalid.
2762 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2763 continue;
2764
2765 // Check if the most recent declaration has changed the specialization kind
2766 // and removed the need for implicit instantiation.
2767 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2768 case TSK_Undeclared:
2769 assert(false && "Cannot instantitiate an undeclared specialization.");
2770 case TSK_ExplicitInstantiationDeclaration:
2771 case TSK_ExplicitInstantiationDefinition:
2772 case TSK_ExplicitSpecialization:
2773 continue; // No longer need implicit instantiation.
2774 case TSK_ImplicitInstantiation:
2775 break;
2776 }
2777
Mike Stump1eb44332009-09-09 15:08:12 +00002778 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002779 Var->getLocation(), *this,
2780 Context.getSourceManager(),
2781 "instantiating static data member "
2782 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Douglas Gregor7caa6822009-07-24 20:34:43 +00002784 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002785 }
2786}
John McCall0c01d182010-03-24 05:22:00 +00002787
2788void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2789 const MultiLevelTemplateArgumentList &TemplateArgs) {
2790 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2791 E = Pattern->ddiag_end(); I != E; ++I) {
2792 DependentDiagnostic *DD = *I;
2793
2794 switch (DD->getKind()) {
2795 case DependentDiagnostic::Access:
2796 HandleDependentAccessCheck(*DD, TemplateArgs);
2797 break;
2798 }
2799 }
2800}