blob: 4209fd7a14b2220e63b68738a30747c84a5adfb1 [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 if (Owner->isFunctionOrMethod())
400 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000401 }
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000402 InstantiateAttrs(D, Var);
403
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
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +0000860 return InstClassTemplate->findPartialSpecInstantiatedFromMember(D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000861}
862
863Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000864TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000865 // Create a local instantiation scope for this function template, which
866 // will contain the instantiations of the template parameters and then get
867 // merged with the local instantiation scope for the function template
868 // itself.
869 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000870
Douglas Gregord60e1052009-08-27 16:57:43 +0000871 TemplateParameterList *TempParams = D->getTemplateParameters();
872 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000873 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000874 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000875
Douglas Gregora735b202009-10-13 14:39:41 +0000876 FunctionDecl *Instantiated = 0;
877 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
878 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
879 InstParams));
880 else
881 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
882 D->getTemplatedDecl(),
883 InstParams));
884
885 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000886 return 0;
887
John McCall46460a62010-01-20 21:53:11 +0000888 Instantiated->setAccess(D->getAccess());
889
Mike Stump1eb44332009-09-09 15:08:12 +0000890 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000891 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000892 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000893 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000894 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000895 assert(InstTemplate &&
896 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000897
John McCallb1a56e72010-03-26 23:10:15 +0000898 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
899
John McCalle976ffe2009-12-14 23:19:40 +0000900 // Link the instantiation back to the pattern *unless* this is a
901 // non-definition friend declaration.
902 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000903 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000904 InstTemplate->setInstantiatedFromMemberTemplate(D);
905
John McCallb1a56e72010-03-26 23:10:15 +0000906 // Make declarations visible in the appropriate context.
907 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000908 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000909
Douglas Gregord60e1052009-08-27 16:57:43 +0000910 return InstTemplate;
911}
912
Douglas Gregord475b8d2009-03-25 21:17:03 +0000913Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
914 CXXRecordDecl *PrevDecl = 0;
915 if (D->isInjectedClassName())
916 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000917 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000918 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
919 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000920 TemplateArgs);
921 if (!Prev) return 0;
922 PrevDecl = cast<CXXRecordDecl>(Prev);
923 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000924
925 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000926 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000927 D->getLocation(), D->getIdentifier(),
928 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000929
930 // Substitute the nested name specifier, if any.
931 if (SubstQualifier(D, Record))
932 return 0;
933
Douglas Gregord475b8d2009-03-25 21:17:03 +0000934 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000935 // FIXME: Check against AS_none is an ugly hack to work around the issue that
936 // the tag decls introduced by friend class declarations don't have an access
937 // specifier. Remove once this area of the code gets sorted out.
938 if (D->getAccess() != AS_none)
939 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000940 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000941 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000942
John McCall02cace72009-08-28 07:59:38 +0000943 // If the original function was part of a friend declaration,
944 // inherit its namespace state.
945 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
946 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
947
Douglas Gregor9901c572010-05-21 00:31:19 +0000948 // Make sure that anonymous structs and unions are recorded.
949 if (D->isAnonymousStructOrUnion()) {
950 Record->setAnonymousStructOrUnion(true);
951 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod())
952 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
953 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000954
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000955 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000956 return Record;
957}
958
John McCall02cace72009-08-28 07:59:38 +0000959/// Normal class members are of more specific types and therefore
960/// don't make it here. This function serves two purposes:
961/// 1) instantiating function templates
962/// 2) substituting friend declarations
963/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000964Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000965 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000966 // Check whether there is already a function template specialization for
967 // this declaration.
968 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
969 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000970 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000971 std::pair<const TemplateArgument *, unsigned> Innermost
972 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000974 FunctionDecl *SpecFunc
975 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
976 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Douglas Gregor127102b2009-06-29 20:59:39 +0000978 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000979 if (SpecFunc)
980 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
John McCallb0cb0222010-03-27 05:57:59 +0000983 bool isFriend;
984 if (FunctionTemplate)
985 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
986 else
987 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
988
Douglas Gregor79c22782010-01-16 20:21:20 +0000989 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000990 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000991 !(isa<Decl>(Owner) &&
992 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
993 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Douglas Gregore53060f2009-06-25 22:08:12 +0000995 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000996 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
997 TInfo = SubstFunctionType(D, Params);
998 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000999 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001000 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001001
John McCalld325daa2010-03-26 04:53:08 +00001002 NestedNameSpecifier *Qualifier = D->getQualifier();
1003 if (Qualifier) {
1004 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1005 D->getQualifierRange(),
1006 TemplateArgs);
1007 if (!Qualifier) return 0;
1008 }
1009
John McCall68b6b872010-02-06 01:50:47 +00001010 // If we're instantiating a local function declaration, put the result
1011 // in the owner; otherwise we need to find the instantiated context.
1012 DeclContext *DC;
1013 if (D->getDeclContext()->isFunctionOrMethod())
1014 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001015 else if (isFriend && Qualifier) {
1016 CXXScopeSpec SS;
1017 SS.setScopeRep(Qualifier);
1018 SS.setRange(D->getQualifierRange());
1019 DC = SemaRef.computeDeclContext(SS);
1020 if (!DC) return 0;
1021 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001022 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1023 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001024 }
John McCall68b6b872010-02-06 01:50:47 +00001025
John McCall02cace72009-08-28 07:59:38 +00001026 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001027 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001028 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001029 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001030 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001031
John McCalld325daa2010-03-26 04:53:08 +00001032 if (Qualifier)
1033 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001034
John McCallb1a56e72010-03-26 23:10:15 +00001035 DeclContext *LexicalDC = Owner;
1036 if (!isFriend && D->isOutOfLine()) {
1037 assert(D->getDeclContext()->isFileContext());
1038 LexicalDC = D->getDeclContext();
1039 }
1040
1041 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Douglas Gregore53060f2009-06-25 22:08:12 +00001043 // Attach the parameters
1044 for (unsigned P = 0; P < Params.size(); ++P)
1045 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001046 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001047
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001048 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001049 if (TemplateParams) {
1050 // Our resulting instantiation is actually a function template, since we
1051 // are substituting only the outer template parameters. For example, given
1052 //
1053 // template<typename T>
1054 // struct X {
1055 // template<typename U> friend void f(T, U);
1056 // };
1057 //
1058 // X<int> x;
1059 //
1060 // We are instantiating the friend function template "f" within X<int>,
1061 // which means substituting int for T, but leaving "f" as a friend function
1062 // template.
1063 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001064 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001065 Function->getLocation(),
1066 Function->getDeclName(),
1067 TemplateParams, Function);
1068 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001069
1070 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001071
1072 if (isFriend && D->isThisDeclarationADefinition()) {
1073 // TODO: should we remember this connection regardless of whether
1074 // the friend declaration provided a body?
1075 FunctionTemplate->setInstantiatedFromMemberTemplate(
1076 D->getDescribedFunctionTemplate());
1077 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001078 } else if (FunctionTemplate) {
1079 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001080 std::pair<const TemplateArgument *, unsigned> Innermost
1081 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001082 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001083 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1084 Innermost.first,
1085 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001086 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001087 } else if (isFriend && D->isThisDeclarationADefinition()) {
1088 // TODO: should we remember this connection regardless of whether
1089 // the friend declaration provided a body?
1090 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001091 }
Douglas Gregora735b202009-10-13 14:39:41 +00001092
Douglas Gregore53060f2009-06-25 22:08:12 +00001093 if (InitFunctionInstantiation(Function, D))
1094 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregore53060f2009-06-25 22:08:12 +00001096 bool Redeclaration = false;
1097 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001098 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001099
John McCall68263142009-11-18 22:49:29 +00001100 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1101 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1102
John McCallaf2094e2010-04-08 09:05:18 +00001103 if (DependentFunctionTemplateSpecializationInfo *Info
1104 = D->getDependentSpecializationInfo()) {
1105 assert(isFriend && "non-friend has dependent specialization info?");
1106
1107 // This needs to be set now for future sanity.
1108 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1109
1110 // Instantiate the explicit template arguments.
1111 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1112 Info->getRAngleLoc());
1113 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1114 TemplateArgumentLoc Loc;
1115 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1116 return 0;
1117
1118 ExplicitArgs.addArgument(Loc);
1119 }
1120
1121 // Map the candidate templates to their instantiations.
1122 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1123 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1124 Info->getTemplate(I),
1125 TemplateArgs);
1126 if (!Temp) return 0;
1127
1128 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1129 }
1130
1131 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1132 &ExplicitArgs,
1133 Previous))
1134 Function->setInvalidDecl();
1135
1136 isExplicitSpecialization = true;
1137
1138 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001139 // Look only into the namespace where the friend would be declared to
1140 // find a previous declaration. This is the innermost enclosing namespace,
1141 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001142 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001143
Douglas Gregora735b202009-10-13 14:39:41 +00001144 // In C++, the previous declaration we find might be a tag type
1145 // (class or enum). In this case, the new declaration will hide the
1146 // tag type. Note that this does does not apply if we're declaring a
1147 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001148 if (Previous.isSingleTagDecl())
1149 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001150 }
1151
John McCall9f54ad42009-12-10 09:41:52 +00001152 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001153 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001154 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001155
John McCall76d32642010-04-24 01:30:58 +00001156 NamedDecl *PrincipalDecl = (TemplateParams
1157 ? cast<NamedDecl>(FunctionTemplate)
1158 : Function);
1159
Douglas Gregora735b202009-10-13 14:39:41 +00001160 // If the original function was part of a friend declaration,
1161 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001162 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001163 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001164 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001165 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001166 else
Douglas Gregora735b202009-10-13 14:39:41 +00001167 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001168
1169 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1170 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001171
1172 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1173 D->isThisDeclarationADefinition()) {
1174 // Check for a function body.
1175 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001176 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001177 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1178 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1179 << Function->getDeclName();
1180 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1181 Function->setInvalidDecl();
1182 }
1183 // Check for redefinitions due to other instantiations of this or
1184 // a similar friend function.
1185 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1186 REnd = Function->redecls_end();
1187 R != REnd; ++R) {
1188 if (*R != Function &&
1189 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1190 if (const FunctionDecl *RPattern
1191 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001192 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001193 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1194 << Function->getDeclName();
1195 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1196 Function->setInvalidDecl();
1197 break;
1198 }
1199 }
1200 }
1201 }
1202
Douglas Gregora735b202009-10-13 14:39:41 +00001203 }
1204
John McCall76d32642010-04-24 01:30:58 +00001205 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1206 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1207 PrincipalDecl->setNonMemberOperator();
1208
Douglas Gregore53060f2009-06-25 22:08:12 +00001209 return Function;
1210}
1211
Douglas Gregord60e1052009-08-27 16:57:43 +00001212Decl *
1213TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1214 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001215 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1216 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001217 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001218 // We are creating a function template specialization from a function
1219 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001220 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001221 std::pair<const TemplateArgument *, unsigned> Innermost
1222 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001224 FunctionDecl *SpecFunc
1225 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1226 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor6b906862009-08-21 00:16:32 +00001228 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001229 if (SpecFunc)
1230 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001231 }
1232
John McCallb0cb0222010-03-27 05:57:59 +00001233 bool isFriend;
1234 if (FunctionTemplate)
1235 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1236 else
1237 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1238
Douglas Gregor79c22782010-01-16 20:21:20 +00001239 bool MergeWithParentScope = (TemplateParams != 0) ||
1240 !(isa<Decl>(Owner) &&
1241 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1242 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001243
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001244 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001245 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1246 TInfo = SubstFunctionType(D, Params);
1247 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001248 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001249 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001250
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001251 // \brief If the type of this function is not *directly* a function
1252 // type, then we're instantiating the a function that was declared
1253 // via a typedef, e.g.,
1254 //
1255 // typedef int functype(int, int);
1256 // functype func;
1257 //
1258 // In this case, we'll just go instantiate the ParmVarDecls that we
1259 // synthesized in the method declaration.
1260 if (!isa<FunctionProtoType>(T)) {
1261 assert(!Params.size() && "Instantiating type could not yield parameters");
1262 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1263 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1264 TemplateArgs);
1265 if (!P)
1266 return 0;
1267
1268 Params.push_back(P);
1269 }
1270 }
1271
John McCallb0cb0222010-03-27 05:57:59 +00001272 NestedNameSpecifier *Qualifier = D->getQualifier();
1273 if (Qualifier) {
1274 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1275 D->getQualifierRange(),
1276 TemplateArgs);
1277 if (!Qualifier) return 0;
1278 }
1279
1280 DeclContext *DC = Owner;
1281 if (isFriend) {
1282 if (Qualifier) {
1283 CXXScopeSpec SS;
1284 SS.setScopeRep(Qualifier);
1285 SS.setRange(D->getQualifierRange());
1286 DC = SemaRef.computeDeclContext(SS);
1287 } else {
1288 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1289 D->getDeclContext(),
1290 TemplateArgs);
1291 }
1292 if (!DC) return 0;
1293 }
1294
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001295 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001296 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001297 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregordec06662009-08-21 18:42:58 +00001299 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001300 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001301 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1302 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1303 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001304 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1305 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001306 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001308 Constructor->isInlineSpecified(),
1309 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001310 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1311 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1312 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1313 SemaRef.Context.getCanonicalType(ClassTy));
1314 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1315 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001316 T, Destructor->isInlineSpecified(),
1317 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001318 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001319 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001320 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001321 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001322 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1323 ConvTy);
1324 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1325 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001326 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001327 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001328 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001329 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001330 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001331 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001332 D->isStatic(),
1333 D->getStorageClassAsWritten(),
1334 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001335 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001336
John McCallb0cb0222010-03-27 05:57:59 +00001337 if (Qualifier)
1338 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001339
Douglas Gregord60e1052009-08-27 16:57:43 +00001340 if (TemplateParams) {
1341 // Our resulting instantiation is actually a function template, since we
1342 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001343 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001344 // template<typename T>
1345 // struct X {
1346 // template<typename U> void f(T, U);
1347 // };
1348 //
1349 // X<int> x;
1350 //
1351 // We are instantiating the member template "f" within X<int>, which means
1352 // substituting int for T, but leaving "f" as a member function template.
1353 // Build the function template itself.
1354 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1355 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001356 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001357 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001358 if (isFriend) {
1359 FunctionTemplate->setLexicalDeclContext(Owner);
1360 FunctionTemplate->setObjectOfFriendDecl(true);
1361 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001362 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001363 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001364 } else if (FunctionTemplate) {
1365 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001366 std::pair<const TemplateArgument *, unsigned> Innermost
1367 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001368 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001369 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1370 Innermost.first,
1371 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001372 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001373 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001374 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001375 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001376 }
1377
Mike Stump1eb44332009-09-09 15:08:12 +00001378 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001379 // out-of-line, the instantiation will have the same lexical
1380 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001381 if (isFriend) {
1382 Method->setLexicalDeclContext(Owner);
1383 Method->setObjectOfFriendDecl(true);
1384 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001385 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor5545e162009-03-24 00:38:23 +00001387 // Attach the parameters
1388 for (unsigned P = 0; P < Params.size(); ++P)
1389 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001390 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001391
1392 if (InitMethodInstantiation(Method, D))
1393 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001394
John McCall68263142009-11-18 22:49:29 +00001395 LookupResult Previous(SemaRef, Name, SourceLocation(),
1396 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
John McCallb0cb0222010-03-27 05:57:59 +00001398 if (!FunctionTemplate || TemplateParams || isFriend) {
1399 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregordec06662009-08-21 18:42:58 +00001401 // In C++, the previous declaration we find might be a tag type
1402 // (class or enum). In this case, the new declaration will hide the
1403 // tag type. Note that this does does not apply if we're declaring a
1404 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001405 if (Previous.isSingleTagDecl())
1406 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001407 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001408
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001409 bool Redeclaration = false;
1410 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001411 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001412 /*FIXME:*/OverloadableAttrRequired);
1413
Douglas Gregor4ba31362009-12-01 17:24:26 +00001414 if (D->isPure())
1415 SemaRef.CheckPureMethod(Method, SourceRange());
1416
John McCall46460a62010-01-20 21:53:11 +00001417 Method->setAccess(D->getAccess());
1418
John McCallb0cb0222010-03-27 05:57:59 +00001419 if (FunctionTemplate) {
1420 // If there's a function template, let our caller handle it.
1421 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1422 // Don't hide a (potentially) valid declaration with an invalid one.
1423 } else {
1424 NamedDecl *DeclToAdd = (TemplateParams
1425 ? cast<NamedDecl>(FunctionTemplate)
1426 : Method);
1427 if (isFriend)
1428 Record->makeDeclVisibleInContext(DeclToAdd);
1429 else
1430 Owner->addDecl(DeclToAdd);
1431 }
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001433 return Method;
1434}
1435
Douglas Gregor615c5d42009-03-24 16:43:20 +00001436Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001437 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001438}
1439
Douglas Gregor03b2b072009-03-24 00:15:49 +00001440Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001441 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001442}
1443
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001444Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001445 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001446}
1447
Douglas Gregor6477b692009-03-25 15:04:13 +00001448ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001449 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001450}
1451
John McCalle29ba202009-08-20 01:44:21 +00001452Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1453 TemplateTypeParmDecl *D) {
1454 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001455 const Type* T = D->getTypeForDecl();
1456 assert(T->isTemplateTypeParmType());
1457 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCalle29ba202009-08-20 01:44:21 +00001459 TemplateTypeParmDecl *Inst =
1460 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001461 TTPT->getDepth() - 1, TTPT->getIndex(),
1462 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001463 D->wasDeclaredWithTypename(),
1464 D->isParameterPack());
1465
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001466 if (D->hasDefaultArgument())
1467 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001468
Douglas Gregor550d9b22009-10-31 17:21:17 +00001469 // Introduce this template parameter's instantiation into the instantiation
1470 // scope.
1471 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1472
John McCalle29ba202009-08-20 01:44:21 +00001473 return Inst;
1474}
1475
Douglas Gregor33642df2009-10-23 23:25:44 +00001476Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1477 NonTypeTemplateParmDecl *D) {
1478 // Substitute into the type of the non-type template parameter.
1479 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001480 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001481 if (DI) {
1482 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1483 D->getDeclName());
1484 if (DI) T = DI->getType();
1485 } else {
1486 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1487 D->getDeclName());
1488 DI = 0;
1489 }
1490 if (T.isNull())
1491 return 0;
1492
1493 // Check that this type is acceptable for a non-type template parameter.
1494 bool Invalid = false;
1495 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1496 if (T.isNull()) {
1497 T = SemaRef.Context.IntTy;
1498 Invalid = true;
1499 }
1500
1501 NonTypeTemplateParmDecl *Param
1502 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1503 D->getDepth() - 1, D->getPosition(),
1504 D->getIdentifier(), T, DI);
1505 if (Invalid)
1506 Param->setInvalidDecl();
1507
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001508 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001509
1510 // Introduce this template parameter's instantiation into the instantiation
1511 // scope.
1512 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001513 return Param;
1514}
1515
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001516Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001517TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1518 TemplateTemplateParmDecl *D) {
1519 // Instantiate the template parameter list of the template template parameter.
1520 TemplateParameterList *TempParams = D->getTemplateParameters();
1521 TemplateParameterList *InstParams;
1522 {
1523 // Perform the actual substitution of template parameters within a new,
1524 // local instantiation scope.
1525 Sema::LocalInstantiationScope Scope(SemaRef);
1526 InstParams = SubstTemplateParams(TempParams);
1527 if (!InstParams)
1528 return NULL;
1529 }
1530
1531 // Build the template template parameter.
1532 TemplateTemplateParmDecl *Param
1533 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1534 D->getDepth() - 1, D->getPosition(),
1535 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001536 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001537
Douglas Gregor9106ef72009-11-11 16:58:32 +00001538 // Introduce this template parameter's instantiation into the instantiation
1539 // scope.
1540 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1541
1542 return Param;
1543}
1544
Douglas Gregor48c32a72009-11-17 06:07:40 +00001545Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1546 // Using directives are never dependent, so they require no explicit
1547
1548 UsingDirectiveDecl *Inst
1549 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1550 D->getNamespaceKeyLocation(),
1551 D->getQualifierRange(), D->getQualifier(),
1552 D->getIdentLocation(),
1553 D->getNominatedNamespace(),
1554 D->getCommonAncestor());
1555 Owner->addDecl(Inst);
1556 return Inst;
1557}
1558
John McCalled976492009-12-04 22:46:56 +00001559Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1560 // The nested name specifier is non-dependent, so no transformation
1561 // is required.
1562
John McCall9f54ad42009-12-10 09:41:52 +00001563 // We only need to do redeclaration lookups if we're in a class
1564 // scope (in fact, it's not really even possible in non-class
1565 // scopes).
1566 bool CheckRedeclaration = Owner->isRecord();
1567
1568 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1569 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1570
John McCalled976492009-12-04 22:46:56 +00001571 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1572 D->getLocation(),
1573 D->getNestedNameRange(),
1574 D->getUsingLocation(),
1575 D->getTargetNestedNameDecl(),
1576 D->getDeclName(),
1577 D->isTypeName());
1578
1579 CXXScopeSpec SS;
1580 SS.setScopeRep(D->getTargetNestedNameDecl());
1581 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001582
1583 if (CheckRedeclaration) {
1584 Prev.setHideTags(false);
1585 SemaRef.LookupQualifiedName(Prev, Owner);
1586
1587 // Check for invalid redeclarations.
1588 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1589 D->isTypeName(), SS,
1590 D->getLocation(), Prev))
1591 NewUD->setInvalidDecl();
1592
1593 }
1594
1595 if (!NewUD->isInvalidDecl() &&
1596 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001597 D->getLocation()))
1598 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001599
John McCalled976492009-12-04 22:46:56 +00001600 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1601 NewUD->setAccess(D->getAccess());
1602 Owner->addDecl(NewUD);
1603
John McCall9f54ad42009-12-10 09:41:52 +00001604 // Don't process the shadow decls for an invalid decl.
1605 if (NewUD->isInvalidDecl())
1606 return NewUD;
1607
John McCall323c3102009-12-22 22:26:37 +00001608 bool isFunctionScope = Owner->isFunctionOrMethod();
1609
John McCall9f54ad42009-12-10 09:41:52 +00001610 // Process the shadow decls.
1611 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1612 I != E; ++I) {
1613 UsingShadowDecl *Shadow = *I;
1614 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001615 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1616 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001617 TemplateArgs));
1618
1619 if (CheckRedeclaration &&
1620 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1621 continue;
1622
1623 UsingShadowDecl *InstShadow
1624 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1625 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001626
1627 if (isFunctionScope)
1628 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001629 }
John McCalled976492009-12-04 22:46:56 +00001630
1631 return NewUD;
1632}
1633
1634Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001635 // Ignore these; we handle them in bulk when processing the UsingDecl.
1636 return 0;
John McCalled976492009-12-04 22:46:56 +00001637}
1638
John McCall7ba107a2009-11-18 02:36:19 +00001639Decl * TemplateDeclInstantiator
1640 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001641 NestedNameSpecifier *NNS =
1642 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1643 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001644 TemplateArgs);
1645 if (!NNS)
1646 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001648 CXXScopeSpec SS;
1649 SS.setRange(D->getTargetNestedNameRange());
1650 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001651
1652 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001653 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001654 D->getUsingLoc(), SS, D->getLocation(),
1655 D->getDeclName(), 0,
1656 /*instantiation*/ true,
1657 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001658 if (UD)
John McCalled976492009-12-04 22:46:56 +00001659 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1660
John McCall7ba107a2009-11-18 02:36:19 +00001661 return UD;
1662}
1663
1664Decl * TemplateDeclInstantiator
1665 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1666 NestedNameSpecifier *NNS =
1667 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1668 D->getTargetNestedNameRange(),
1669 TemplateArgs);
1670 if (!NNS)
1671 return 0;
1672
1673 CXXScopeSpec SS;
1674 SS.setRange(D->getTargetNestedNameRange());
1675 SS.setScopeRep(NNS);
1676
1677 NamedDecl *UD =
1678 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1679 D->getUsingLoc(), SS, D->getLocation(),
1680 D->getDeclName(), 0,
1681 /*instantiation*/ true,
1682 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001683 if (UD)
John McCalled976492009-12-04 22:46:56 +00001684 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1685
Anders Carlsson0d8df782009-08-29 19:37:28 +00001686 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001687}
1688
John McCallce3ff2b2009-08-25 22:02:44 +00001689Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001690 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001691 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001692 if (D->isInvalidDecl())
1693 return 0;
1694
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001695 return Instantiator.Visit(D);
1696}
1697
John McCalle29ba202009-08-20 01:44:21 +00001698/// \brief Instantiates a nested template parameter list in the current
1699/// instantiation context.
1700///
1701/// \param L The parameter list to instantiate
1702///
1703/// \returns NULL if there was an error
1704TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001705TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001706 // Get errors for all the parameters before bailing out.
1707 bool Invalid = false;
1708
1709 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001710 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001711 ParamVector Params;
1712 Params.reserve(N);
1713 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1714 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001715 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001716 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001717 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001718 }
1719
1720 // Clean up if we had an error.
1721 if (Invalid) {
1722 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1723 PI != PE; ++PI)
1724 if (*PI)
1725 (*PI)->Destroy(SemaRef.Context);
1726 return NULL;
1727 }
1728
1729 TemplateParameterList *InstL
1730 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1731 L->getLAngleLoc(), &Params.front(), N,
1732 L->getRAngleLoc());
1733 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001734}
John McCalle29ba202009-08-20 01:44:21 +00001735
Douglas Gregored9c0f92009-10-29 00:04:11 +00001736/// \brief Instantiate the declaration of a class template partial
1737/// specialization.
1738///
1739/// \param ClassTemplate the (instantiated) class template that is partially
1740// specialized by the instantiation of \p PartialSpec.
1741///
1742/// \param PartialSpec the (uninstantiated) class template partial
1743/// specialization that we are instantiating.
1744///
1745/// \returns true if there was an error, false otherwise.
1746bool
1747TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1748 ClassTemplateDecl *ClassTemplate,
1749 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001750 // Create a local instantiation scope for this class template partial
1751 // specialization, which will contain the instantiations of the template
1752 // parameters.
1753 Sema::LocalInstantiationScope Scope(SemaRef);
1754
Douglas Gregored9c0f92009-10-29 00:04:11 +00001755 // Substitute into the template parameters of the class template partial
1756 // specialization.
1757 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1758 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1759 if (!InstParams)
1760 return true;
1761
1762 // Substitute into the template arguments of the class template partial
1763 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001764 const TemplateArgumentLoc *PartialSpecTemplateArgs
1765 = PartialSpec->getTemplateArgsAsWritten();
1766 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1767
John McCalld5532b62009-11-23 01:53:49 +00001768 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001769 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001770 TemplateArgumentLoc Loc;
1771 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001772 return true;
John McCalld5532b62009-11-23 01:53:49 +00001773 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001774 }
1775
1776
1777 // Check that the template argument list is well-formed for this
1778 // class template.
1779 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1780 InstTemplateArgs.size());
1781 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1782 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001783 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001784 false,
1785 Converted))
1786 return true;
1787
1788 // Figure out where to insert this class template partial specialization
1789 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001790 void *InsertPos = 0;
1791 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001792 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1793 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001794
1795 // Build the canonical type that describes the converted template
1796 // arguments of the class template partial specialization.
1797 QualType CanonType
1798 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1799 Converted.getFlatArguments(),
1800 Converted.flatSize());
1801
1802 // Build the fully-sugared type for this class template
1803 // specialization as the user wrote in the specialization
1804 // itself. This means that we'll pretty-print the type retrieved
1805 // from the specialization's declaration the way that the user
1806 // actually wrote the specialization, rather than formatting the
1807 // name based on the "canonical" representation used to store the
1808 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001809 TypeSourceInfo *WrittenTy
1810 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1811 TemplateName(ClassTemplate),
1812 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001813 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001814 CanonType);
1815
1816 if (PrevDecl) {
1817 // We've already seen a partial specialization with the same template
1818 // parameters and template arguments. This can happen, for example, when
1819 // substituting the outer template arguments ends up causing two
1820 // class template partial specializations of a member class template
1821 // to have identical forms, e.g.,
1822 //
1823 // template<typename T, typename U>
1824 // struct Outer {
1825 // template<typename X, typename Y> struct Inner;
1826 // template<typename Y> struct Inner<T, Y>;
1827 // template<typename Y> struct Inner<U, Y>;
1828 // };
1829 //
1830 // Outer<int, int> outer; // error: the partial specializations of Inner
1831 // // have the same signature.
1832 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1833 << WrittenTy;
1834 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1835 << SemaRef.Context.getTypeDeclType(PrevDecl);
1836 return true;
1837 }
1838
1839
1840 // Create the class template partial specialization declaration.
1841 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001842 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1843 PartialSpec->getTagKind(),
1844 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001845 PartialSpec->getLocation(),
1846 InstParams,
1847 ClassTemplate,
1848 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001849 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001850 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001851 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001852 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001853 // Substitute the nested name specifier, if any.
1854 if (SubstQualifier(PartialSpec, InstPartialSpec))
1855 return 0;
1856
Douglas Gregored9c0f92009-10-29 00:04:11 +00001857 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001858 InstPartialSpec->setTypeAsWritten(WrittenTy);
1859
Douglas Gregored9c0f92009-10-29 00:04:11 +00001860 // Add this partial specialization to the set of class template partial
1861 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001862 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001863 return false;
1864}
1865
John McCall21ef0fa2010-03-11 09:03:00 +00001866TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001867TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001868 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001869 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1870 assert(OldTInfo && "substituting function without type source info");
1871 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001872 TypeSourceInfo *NewTInfo
1873 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1874 D->getTypeSpecStartLoc(),
1875 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001876 if (!NewTInfo)
1877 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001878
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001879 if (NewTInfo != OldTInfo) {
1880 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001881 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001882 if (FunctionProtoTypeLoc *OldProtoLoc
1883 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1884 TypeLoc NewTL = NewTInfo->getTypeLoc();
1885 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1886 assert(NewProtoLoc && "Missing prototype?");
1887 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1888 // FIXME: Variadic templates will break this.
1889 Params.push_back(NewProtoLoc->getArg(i));
1890 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001891 OldProtoLoc->getArg(i),
1892 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001893 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001894 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001895 } else {
1896 // The function type itself was not dependent and therefore no
1897 // substitution occurred. However, we still need to instantiate
1898 // the function parameters themselves.
1899 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001900 if (FunctionProtoTypeLoc *OldProtoLoc
1901 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1902 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1903 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1904 if (!Parm)
1905 return 0;
1906 Params.push_back(Parm);
1907 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001908 }
1909 }
John McCall21ef0fa2010-03-11 09:03:00 +00001910 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001911}
1912
Mike Stump1eb44332009-09-09 15:08:12 +00001913/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001914/// declaration (New) from the corresponding fields of its template (Tmpl).
1915///
1916/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001917bool
1918TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001919 FunctionDecl *Tmpl) {
1920 if (Tmpl->isDeleted())
1921 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregorcca9e962009-07-01 22:01:06 +00001923 // If we are performing substituting explicitly-specified template arguments
1924 // or deduced template arguments into a function template and we reach this
1925 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001926 // to keeping the new function template specialization. We therefore
1927 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001928 // into a template instantiation for this specific function template
1929 // specialization, which is not a SFINAE context, so that we diagnose any
1930 // further errors in the declaration itself.
1931 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1932 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1933 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1934 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001935 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001936 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001937 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001938 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001939 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001940 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1941 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001942 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001943 }
1944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001946 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1947 assert(Proto && "Function template without prototype?");
1948
1949 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1950 Proto->getNoReturnAttr()) {
1951 // The function has an exception specification or a "noreturn"
1952 // attribute. Substitute into each of the exception types.
1953 llvm::SmallVector<QualType, 4> Exceptions;
1954 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1955 // FIXME: Poor location information!
1956 QualType T
1957 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1958 New->getLocation(), New->getDeclName());
1959 if (T.isNull() ||
1960 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1961 continue;
1962
1963 Exceptions.push_back(T);
1964 }
1965
1966 // Rebuild the function type
1967
1968 const FunctionProtoType *NewProto
1969 = New->getType()->getAs<FunctionProtoType>();
1970 assert(NewProto && "Template instantiation without function prototype?");
1971 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1972 NewProto->arg_type_begin(),
1973 NewProto->getNumArgs(),
1974 NewProto->isVariadic(),
1975 NewProto->getTypeQuals(),
1976 Proto->hasExceptionSpec(),
1977 Proto->hasAnyExceptionSpec(),
1978 Exceptions.size(),
1979 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001980 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001981 }
1982
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001983 InstantiateAttrs(Tmpl, New);
1984
Douglas Gregore53060f2009-06-25 22:08:12 +00001985 return false;
1986}
1987
Douglas Gregor5545e162009-03-24 00:38:23 +00001988/// \brief Initializes common fields of an instantiated method
1989/// declaration (New) from the corresponding fields of its template
1990/// (Tmpl).
1991///
1992/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001993bool
1994TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001995 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001996 if (InitFunctionInstantiation(New, Tmpl))
1997 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Douglas Gregor5545e162009-03-24 00:38:23 +00001999 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
2000 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002001 if (Tmpl->isVirtualAsWritten())
2002 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00002003
2004 // FIXME: attributes
2005 // FIXME: New needs a pointer to Tmpl
2006 return false;
2007}
Douglas Gregora58861f2009-05-13 20:28:22 +00002008
2009/// \brief Instantiate the definition of the given function from its
2010/// template.
2011///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002012/// \param PointOfInstantiation the point at which the instantiation was
2013/// required. Note that this is not precisely a "point of instantiation"
2014/// for the function, but it's close.
2015///
Douglas Gregora58861f2009-05-13 20:28:22 +00002016/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002017/// function template specialization or member function of a class template
2018/// specialization.
2019///
2020/// \param Recursive if true, recursively instantiates any functions that
2021/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002022///
2023/// \param DefinitionRequired if true, then we are performing an explicit
2024/// instantiation where the body of the function is required. Complain if
2025/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002026void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002027 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002028 bool Recursive,
2029 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002030 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002031 return;
2032
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002033 // Never instantiate an explicit specialization.
2034 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2035 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002036
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002037 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002038 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002039 Stmt *Pattern = 0;
2040 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002041 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002042
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002043 if (!Pattern) {
2044 if (DefinitionRequired) {
2045 if (Function->getPrimaryTemplate())
2046 Diag(PointOfInstantiation,
2047 diag::err_explicit_instantiation_undefined_func_template)
2048 << Function->getPrimaryTemplate();
2049 else
2050 Diag(PointOfInstantiation,
2051 diag::err_explicit_instantiation_undefined_member)
2052 << 1 << Function->getDeclName() << Function->getDeclContext();
2053
2054 if (PatternDecl)
2055 Diag(PatternDecl->getLocation(),
2056 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002057 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002058 }
2059
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002060 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002061 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002062
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002063 // C++0x [temp.explicit]p9:
2064 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002065 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002066 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002067 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002068 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002069 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002070 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002072 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2073 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002074 return;
2075
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002076 // If we're performing recursive template instantiation, create our own
2077 // queue of pending implicit instantiations that we will instantiate later,
2078 // while we're still within our own instantiation context.
2079 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2080 if (Recursive)
2081 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Douglas Gregor9679caf2010-05-12 17:27:19 +00002083 EnterExpressionEvaluationContext EvalContext(*this,
2084 Action::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002085 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2086
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002087 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002088 // recorded, unless we're actually a member function within a local
2089 // class, in which case we need to merge our results with the parent
2090 // scope (of the enclosing function).
2091 bool MergeWithParentScope = false;
2092 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2093 MergeWithParentScope = Rec->isLocalClass();
2094
2095 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002097 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002098 // instantiation scope, and set the parameter names to those used
2099 // in the template.
2100 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2101 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2102 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2103 FunctionParam->setDeclName(PatternParam->getDeclName());
2104 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2105 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002106
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002107 // Enter the scope of this instantiation. We don't use
2108 // PushDeclContext because we don't have a scope.
2109 DeclContext *PreviousContext = CurContext;
2110 CurContext = Function;
2111
Mike Stump1eb44332009-09-09 15:08:12 +00002112 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002113 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002114
2115 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002116 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002117 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2118 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2119 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002120 }
2121
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002122 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002123 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002124
Douglas Gregor52604ab2009-09-11 21:19:12 +00002125 if (Body.isInvalid())
2126 Function->setInvalidDecl();
2127
Mike Stump1eb44332009-09-09 15:08:12 +00002128 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002129 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002130
John McCall0c01d182010-03-24 05:22:00 +00002131 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2132
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002133 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002134
2135 DeclGroupRef DG(Function);
2136 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregor60406be2010-01-16 22:29:39 +00002138 // This class may have local implicit instantiations that need to be
2139 // instantiation within this scope.
2140 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2141 Scope.Exit();
2142
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002143 if (Recursive) {
2144 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002145 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002146 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002148 // Restore the set of pending implicit instantiations.
2149 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2150 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002151}
2152
2153/// \brief Instantiate the definition of the given variable from its
2154/// template.
2155///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002156/// \param PointOfInstantiation the point at which the instantiation was
2157/// required. Note that this is not precisely a "point of instantiation"
2158/// for the function, but it's close.
2159///
2160/// \param Var the already-instantiated declaration of a static member
2161/// variable of a class template specialization.
2162///
2163/// \param Recursive if true, recursively instantiates any functions that
2164/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002165///
2166/// \param DefinitionRequired if true, then we are performing an explicit
2167/// instantiation where an out-of-line definition of the member variable
2168/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002169void Sema::InstantiateStaticDataMemberDefinition(
2170 SourceLocation PointOfInstantiation,
2171 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002172 bool Recursive,
2173 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002174 if (Var->isInvalidDecl())
2175 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Douglas Gregor7caa6822009-07-24 20:34:43 +00002177 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002178 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002179 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002180 assert(Def->isStaticDataMember() && "Not a static data member?");
2181 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Douglas Gregor0d035142009-10-27 18:42:08 +00002183 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002184 // We did not find an out-of-line definition of this static data member,
2185 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002186 // instantiate this definition (or provide a specialization for it) in
2187 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002188 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002189 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002190 Diag(PointOfInstantiation,
2191 diag::err_explicit_instantiation_undefined_member)
2192 << 2 << Var->getDeclName() << Var->getDeclContext();
2193 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2194 }
2195
Douglas Gregor7caa6822009-07-24 20:34:43 +00002196 return;
2197 }
2198
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002199 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002200 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002201 return;
2202
2203 // C++0x [temp.explicit]p9:
2204 // Except for inline functions, other explicit instantiation declarations
2205 // have the effect of suppressing the implicit instantiation of the entity
2206 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002207 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002208 == TSK_ExplicitInstantiationDeclaration)
2209 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Douglas Gregor7caa6822009-07-24 20:34:43 +00002211 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2212 if (Inst)
2213 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor7caa6822009-07-24 20:34:43 +00002215 // If we're performing recursive template instantiation, create our own
2216 // queue of pending implicit instantiations that we will instantiate later,
2217 // while we're still within our own instantiation context.
2218 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2219 if (Recursive)
2220 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregor7caa6822009-07-24 20:34:43 +00002222 // Enter the scope of this instantiation. We don't use
2223 // PushDeclContext because we don't have a scope.
2224 DeclContext *PreviousContext = CurContext;
2225 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002227 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002228 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002229 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002230 CurContext = PreviousContext;
2231
2232 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002233 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2234 assert(MSInfo && "Missing member specialization information?");
2235 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2236 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002237 DeclGroupRef DG(Var);
2238 Consumer.HandleTopLevelDecl(DG);
2239 }
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Douglas Gregor7caa6822009-07-24 20:34:43 +00002241 if (Recursive) {
2242 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002243 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002244 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregor7caa6822009-07-24 20:34:43 +00002246 // Restore the set of pending implicit instantiations.
2247 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002248 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002249}
Douglas Gregor815215d2009-05-27 05:35:12 +00002250
Anders Carlsson09025312009-08-29 05:16:22 +00002251void
2252Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2253 const CXXConstructorDecl *Tmpl,
2254 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Anders Carlsson09025312009-08-29 05:16:22 +00002256 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002257 bool AnyErrors = false;
2258
Anders Carlsson09025312009-08-29 05:16:22 +00002259 // Instantiate all the initializers.
2260 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002261 InitsEnd = Tmpl->init_end();
2262 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002263 CXXBaseOrMemberInitializer *Init = *Inits;
2264
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002265 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002266 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002267 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002269 // Instantiate the initializer.
2270 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2271 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2272 AnyErrors = true;
2273 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002274 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002275
Anders Carlsson09025312009-08-29 05:16:22 +00002276 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002277 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002278 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002279 TemplateArgs,
2280 Init->getSourceLocation(),
2281 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002282 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002283 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002284 New->setInvalidDecl();
2285 continue;
2286 }
2287
John McCalla93c9342009-12-07 02:54:59 +00002288 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002289 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002290 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002291 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002292 Init->getRParenLoc(),
2293 New->getParent());
2294 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002295 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002297 // Is this an anonymous union?
2298 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002299 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2300 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002301 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002302 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2303 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002304 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002305
2306 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002307 NewArgs.size(),
2308 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002309 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002310 Init->getRParenLoc());
2311 }
2312
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313 if (NewInit.isInvalid()) {
2314 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002315 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002316 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002317 // FIXME: It would be nice if ASTOwningVector had a release function.
2318 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Anders Carlsson09025312009-08-29 05:16:22 +00002320 NewInits.push_back((MemInitTy *)NewInit.get());
2321 }
2322 }
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Anders Carlsson09025312009-08-29 05:16:22 +00002324 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002325 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002326 /*FIXME: ColonLoc */
2327 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002328 NewInits.data(), NewInits.size(),
2329 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002330}
2331
John McCall52a575a2009-08-29 08:11:13 +00002332// TODO: this could be templated if the various decl types used the
2333// same method name.
2334static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2335 ClassTemplateDecl *Instance) {
2336 Pattern = Pattern->getCanonicalDecl();
2337
2338 do {
2339 Instance = Instance->getCanonicalDecl();
2340 if (Pattern == Instance) return true;
2341 Instance = Instance->getInstantiatedFromMemberTemplate();
2342 } while (Instance);
2343
2344 return false;
2345}
2346
Douglas Gregor0d696532009-09-28 06:34:35 +00002347static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2348 FunctionTemplateDecl *Instance) {
2349 Pattern = Pattern->getCanonicalDecl();
2350
2351 do {
2352 Instance = Instance->getCanonicalDecl();
2353 if (Pattern == Instance) return true;
2354 Instance = Instance->getInstantiatedFromMemberTemplate();
2355 } while (Instance);
2356
2357 return false;
2358}
2359
Douglas Gregored9c0f92009-10-29 00:04:11 +00002360static bool
2361isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2362 ClassTemplatePartialSpecializationDecl *Instance) {
2363 Pattern
2364 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2365 do {
2366 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2367 Instance->getCanonicalDecl());
2368 if (Pattern == Instance)
2369 return true;
2370 Instance = Instance->getInstantiatedFromMember();
2371 } while (Instance);
2372
2373 return false;
2374}
2375
John McCall52a575a2009-08-29 08:11:13 +00002376static bool isInstantiationOf(CXXRecordDecl *Pattern,
2377 CXXRecordDecl *Instance) {
2378 Pattern = Pattern->getCanonicalDecl();
2379
2380 do {
2381 Instance = Instance->getCanonicalDecl();
2382 if (Pattern == Instance) return true;
2383 Instance = Instance->getInstantiatedFromMemberClass();
2384 } while (Instance);
2385
2386 return false;
2387}
2388
2389static bool isInstantiationOf(FunctionDecl *Pattern,
2390 FunctionDecl *Instance) {
2391 Pattern = Pattern->getCanonicalDecl();
2392
2393 do {
2394 Instance = Instance->getCanonicalDecl();
2395 if (Pattern == Instance) return true;
2396 Instance = Instance->getInstantiatedFromMemberFunction();
2397 } while (Instance);
2398
2399 return false;
2400}
2401
2402static bool isInstantiationOf(EnumDecl *Pattern,
2403 EnumDecl *Instance) {
2404 Pattern = Pattern->getCanonicalDecl();
2405
2406 do {
2407 Instance = Instance->getCanonicalDecl();
2408 if (Pattern == Instance) return true;
2409 Instance = Instance->getInstantiatedFromMemberEnum();
2410 } while (Instance);
2411
2412 return false;
2413}
2414
John McCalled976492009-12-04 22:46:56 +00002415static bool isInstantiationOf(UsingShadowDecl *Pattern,
2416 UsingShadowDecl *Instance,
2417 ASTContext &C) {
2418 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2419}
2420
2421static bool isInstantiationOf(UsingDecl *Pattern,
2422 UsingDecl *Instance,
2423 ASTContext &C) {
2424 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2425}
2426
John McCall7ba107a2009-11-18 02:36:19 +00002427static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2428 UsingDecl *Instance,
2429 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002430 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002431}
2432
2433static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002434 UsingDecl *Instance,
2435 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002436 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002437}
2438
John McCall52a575a2009-08-29 08:11:13 +00002439static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2440 VarDecl *Instance) {
2441 assert(Instance->isStaticDataMember());
2442
2443 Pattern = Pattern->getCanonicalDecl();
2444
2445 do {
2446 Instance = Instance->getCanonicalDecl();
2447 if (Pattern == Instance) return true;
2448 Instance = Instance->getInstantiatedFromStaticDataMember();
2449 } while (Instance);
2450
2451 return false;
2452}
2453
John McCalled976492009-12-04 22:46:56 +00002454// Other is the prospective instantiation
2455// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002456static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002457 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002458 if (UnresolvedUsingTypenameDecl *UUD
2459 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2460 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2461 return isInstantiationOf(UUD, UD, Ctx);
2462 }
2463 }
2464
2465 if (UnresolvedUsingValueDecl *UUD
2466 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002467 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2468 return isInstantiationOf(UUD, UD, Ctx);
2469 }
2470 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002471
Anders Carlsson0d8df782009-08-29 19:37:28 +00002472 return false;
2473 }
Mike Stump1eb44332009-09-09 15:08:12 +00002474
John McCall52a575a2009-08-29 08:11:13 +00002475 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2476 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002477
John McCall52a575a2009-08-29 08:11:13 +00002478 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2479 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002480
John McCall52a575a2009-08-29 08:11:13 +00002481 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2482 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002483
Douglas Gregor7caa6822009-07-24 20:34:43 +00002484 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002485 if (Var->isStaticDataMember())
2486 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2487
2488 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2489 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002490
Douglas Gregor0d696532009-09-28 06:34:35 +00002491 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2492 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2493
Douglas Gregored9c0f92009-10-29 00:04:11 +00002494 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2495 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2496 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2497 PartialSpec);
2498
Anders Carlssond8b285f2009-09-01 04:26:58 +00002499 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2500 if (!Field->getDeclName()) {
2501 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002502 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002503 cast<FieldDecl>(D);
2504 }
2505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
John McCalled976492009-12-04 22:46:56 +00002507 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2508 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2509
2510 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2511 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2512
Douglas Gregor815215d2009-05-27 05:35:12 +00002513 return D->getDeclName() && isa<NamedDecl>(Other) &&
2514 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2515}
2516
2517template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002518static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002519 NamedDecl *D,
2520 ForwardIterator first,
2521 ForwardIterator last) {
2522 for (; first != last; ++first)
2523 if (isInstantiationOf(Ctx, D, *first))
2524 return cast<NamedDecl>(*first);
2525
2526 return 0;
2527}
2528
John McCall02cace72009-08-28 07:59:38 +00002529/// \brief Finds the instantiation of the given declaration context
2530/// within the current instantiation.
2531///
2532/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002533DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002534 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002535 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002536 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002537 return cast_or_null<DeclContext>(ID);
2538 } else return DC;
2539}
2540
Douglas Gregored961e72009-05-27 17:54:46 +00002541/// \brief Find the instantiation of the given declaration within the
2542/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002543///
2544/// This routine is intended to be used when \p D is a declaration
2545/// referenced from within a template, that needs to mapped into the
2546/// corresponding declaration within an instantiation. For example,
2547/// given:
2548///
2549/// \code
2550/// template<typename T>
2551/// struct X {
2552/// enum Kind {
2553/// KnownValue = sizeof(T)
2554/// };
2555///
2556/// bool getKind() const { return KnownValue; }
2557/// };
2558///
2559/// template struct X<int>;
2560/// \endcode
2561///
2562/// In the instantiation of X<int>::getKind(), we need to map the
2563/// EnumConstantDecl for KnownValue (which refers to
2564/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002565/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2566/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002567NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002568 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002569 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002570 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002571 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002572 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002573 // D is a local of some kind. Look into the map of local
2574 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002575 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002576 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002577
Douglas Gregore95b4092009-09-16 18:34:49 +00002578 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2579 if (!Record->isDependentContext())
2580 return D;
2581
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002582 // If the RecordDecl is actually the injected-class-name or a
2583 // "templated" declaration for a class template, class template
2584 // partial specialization, or a member class of a class template,
2585 // substitute into the injected-class-name of the class template
2586 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002587 QualType T;
2588 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2589
2590 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002591 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002592 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2593 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002594 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002595
2596 // If we call SubstType with an InjectedClassNameType here we
2597 // can end up in an infinite loop.
2598 T = Context.getTypeDeclType(Record);
2599 assert(isa<InjectedClassNameType>(T) &&
2600 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002601 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002602 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002603
2604 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002605 // Substitute into the injected-class-name to get the type
2606 // corresponding to the instantiation we want, which may also be
2607 // the current instantiation (if we're in a template
2608 // definition). This substitution should never fail, since we
2609 // know we can instantiate the injected-class-name or we
2610 // wouldn't have gotten to the injected-class-name!
2611
2612 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2613 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002614 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2615 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2616
2617 if (!T->isDependentType()) {
2618 assert(T->isRecordType() && "Instantiation must produce a record type");
2619 return T->getAs<RecordType>()->getDecl();
2620 }
2621
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002622 // We are performing "partial" template instantiation to create
2623 // the member declarations for the members of a class template
2624 // specialization. Therefore, D is actually referring to something
2625 // in the current instantiation. Look through the current
2626 // context, which contains actual instantiations, to find the
2627 // instantiation of the "current instantiation" that D refers
2628 // to.
2629 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002630 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002631 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002632 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002633 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002634 if (isInstantiationOf(ClassTemplate,
2635 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002636 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002637
2638 if (!DC->isDependentContext())
2639 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002640 }
2641
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002642 // We're performing "instantiation" of a member of the current
2643 // instantiation while we are type-checking the
2644 // definition. Compute the declaration context and return that.
2645 assert(!SawNonDependentContext &&
2646 "No dependent context while instantiating record");
2647 DeclContext *DC = computeDeclContext(T);
2648 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002649 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002650 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002651 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002652
Douglas Gregore95b4092009-09-16 18:34:49 +00002653 // Fall through to deal with other dependent record types (e.g.,
2654 // anonymous unions in class templates).
2655 }
John McCall52a575a2009-08-29 08:11:13 +00002656
Douglas Gregore95b4092009-09-16 18:34:49 +00002657 if (!ParentDC->isDependentContext())
2658 return D;
2659
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002660 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002661 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002662 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Douglas Gregor815215d2009-05-27 05:35:12 +00002664 if (ParentDC != D->getDeclContext()) {
2665 // We performed some kind of instantiation in the parent context,
2666 // so now we need to look into the instantiated parent context to
2667 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002668
John McCall3cb0ebd2010-03-10 03:28:59 +00002669 // If our context used to be dependent, we may need to instantiate
2670 // it before performing lookup into that context.
2671 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002672 if (!Spec->isDependentContext()) {
2673 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002674 const RecordType *Tag = T->getAs<RecordType>();
2675 assert(Tag && "type of non-dependent record is not a RecordType");
2676 if (!Tag->isBeingDefined() &&
2677 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2678 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002679 }
2680 }
2681
Douglas Gregor815215d2009-05-27 05:35:12 +00002682 NamedDecl *Result = 0;
2683 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002684 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002685 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2686 } else {
2687 // Since we don't have a name for the entity we're looking for,
2688 // our only option is to walk through all of the declarations to
2689 // find that name. This will occur in a few cases:
2690 //
2691 // - anonymous struct/union within a template
2692 // - unnamed class/struct/union/enum within a template
2693 //
2694 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002695 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002696 ParentDC->decls_begin(),
2697 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002698 }
Mike Stump1eb44332009-09-09 15:08:12 +00002699
John McCall9f54ad42009-12-10 09:41:52 +00002700 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002701 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2702 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002703 && "Unable to find instantiation of declaration!");
2704
Douglas Gregor815215d2009-05-27 05:35:12 +00002705 D = Result;
2706 }
2707
Douglas Gregor815215d2009-05-27 05:35:12 +00002708 return D;
2709}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002710
Mike Stump1eb44332009-09-09 15:08:12 +00002711/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002712/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002713void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2714 while (!PendingLocalImplicitInstantiations.empty() ||
2715 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2716 PendingImplicitInstantiation Inst;
2717
2718 if (PendingLocalImplicitInstantiations.empty()) {
2719 Inst = PendingImplicitInstantiations.front();
2720 PendingImplicitInstantiations.pop_front();
2721 } else {
2722 Inst = PendingLocalImplicitInstantiations.front();
2723 PendingLocalImplicitInstantiations.pop_front();
2724 }
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregor7caa6822009-07-24 20:34:43 +00002726 // Instantiate function definitions
2727 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002728 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002729 Function->getLocation(), *this,
2730 Context.getSourceManager(),
2731 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002733 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002734 continue;
2735 }
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Douglas Gregor7caa6822009-07-24 20:34:43 +00002737 // Instantiate static data member definitions.
2738 VarDecl *Var = cast<VarDecl>(Inst.first);
2739 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002740
Chandler Carruth291b4412010-02-13 10:17:50 +00002741 // Don't try to instantiate declarations if the most recent redeclaration
2742 // is invalid.
2743 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2744 continue;
2745
2746 // Check if the most recent declaration has changed the specialization kind
2747 // and removed the need for implicit instantiation.
2748 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2749 case TSK_Undeclared:
2750 assert(false && "Cannot instantitiate an undeclared specialization.");
2751 case TSK_ExplicitInstantiationDeclaration:
2752 case TSK_ExplicitInstantiationDefinition:
2753 case TSK_ExplicitSpecialization:
2754 continue; // No longer need implicit instantiation.
2755 case TSK_ImplicitInstantiation:
2756 break;
2757 }
2758
Mike Stump1eb44332009-09-09 15:08:12 +00002759 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002760 Var->getLocation(), *this,
2761 Context.getSourceManager(),
2762 "instantiating static data member "
2763 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregor7caa6822009-07-24 20:34:43 +00002765 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002766 }
2767}
John McCall0c01d182010-03-24 05:22:00 +00002768
2769void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2770 const MultiLevelTemplateArgumentList &TemplateArgs) {
2771 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2772 E = Pattern->ddiag_end(); I != E; ++I) {
2773 DependentDiagnostic *DD = *I;
2774
2775 switch (DD->getKind()) {
2776 case DependentDiagnostic::Access:
2777 HandleDependentAccessCheck(*DD, TemplateArgs);
2778 break;
2779 }
2780 }
2781}