blob: 7e0617568bf7b1e4889eca8971b1aeffb0c17bac [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 Gregor127102b2009-06-29 20:59:39 +0000971 llvm::FoldingSetNodeID ID;
Douglas Gregor24bae922010-07-08 18:37:38 +0000972 std::pair<const TemplateArgument *, unsigned> Innermost
973 = TemplateArgs.getInnermost();
974 FunctionTemplateSpecializationInfo::Profile(ID, Innermost.first,
975 Innermost.second,
Douglas Gregor828e2262009-07-29 16:09:57 +0000976 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
978 FunctionTemplateSpecializationInfo *Info
979 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000980 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Douglas Gregor127102b2009-06-29 20:59:39 +0000982 // If we already have a function template specialization, return it.
983 if (Info)
984 return Info->Function;
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
John McCallb0cb0222010-03-27 05:57:59 +0000987 bool isFriend;
988 if (FunctionTemplate)
989 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
990 else
991 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
992
Douglas Gregor79c22782010-01-16 20:21:20 +0000993 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000994 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000995 !(isa<Decl>(Owner) &&
996 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
997 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Douglas Gregore53060f2009-06-25 22:08:12 +0000999 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001000 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1001 TInfo = SubstFunctionType(D, Params);
1002 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001003 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001004 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001005
John McCalld325daa2010-03-26 04:53:08 +00001006 NestedNameSpecifier *Qualifier = D->getQualifier();
1007 if (Qualifier) {
1008 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1009 D->getQualifierRange(),
1010 TemplateArgs);
1011 if (!Qualifier) return 0;
1012 }
1013
John McCall68b6b872010-02-06 01:50:47 +00001014 // If we're instantiating a local function declaration, put the result
1015 // in the owner; otherwise we need to find the instantiated context.
1016 DeclContext *DC;
1017 if (D->getDeclContext()->isFunctionOrMethod())
1018 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001019 else if (isFriend && Qualifier) {
1020 CXXScopeSpec SS;
1021 SS.setScopeRep(Qualifier);
1022 SS.setRange(D->getQualifierRange());
1023 DC = SemaRef.computeDeclContext(SS);
1024 if (!DC) return 0;
1025 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001026 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1027 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001028 }
John McCall68b6b872010-02-06 01:50:47 +00001029
John McCall02cace72009-08-28 07:59:38 +00001030 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001031 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001032 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001033 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001034 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001035
John McCalld325daa2010-03-26 04:53:08 +00001036 if (Qualifier)
1037 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001038
John McCallb1a56e72010-03-26 23:10:15 +00001039 DeclContext *LexicalDC = Owner;
1040 if (!isFriend && D->isOutOfLine()) {
1041 assert(D->getDeclContext()->isFileContext());
1042 LexicalDC = D->getDeclContext();
1043 }
1044
1045 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Douglas Gregore53060f2009-06-25 22:08:12 +00001047 // Attach the parameters
1048 for (unsigned P = 0; P < Params.size(); ++P)
1049 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001050 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001051
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001052 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001053 if (TemplateParams) {
1054 // Our resulting instantiation is actually a function template, since we
1055 // are substituting only the outer template parameters. For example, given
1056 //
1057 // template<typename T>
1058 // struct X {
1059 // template<typename U> friend void f(T, U);
1060 // };
1061 //
1062 // X<int> x;
1063 //
1064 // We are instantiating the friend function template "f" within X<int>,
1065 // which means substituting int for T, but leaving "f" as a friend function
1066 // template.
1067 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001068 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001069 Function->getLocation(),
1070 Function->getDeclName(),
1071 TemplateParams, Function);
1072 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001073
1074 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001075
1076 if (isFriend && D->isThisDeclarationADefinition()) {
1077 // TODO: should we remember this connection regardless of whether
1078 // the friend declaration provided a body?
1079 FunctionTemplate->setInstantiatedFromMemberTemplate(
1080 D->getDescribedFunctionTemplate());
1081 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001082 } else if (FunctionTemplate) {
1083 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001084 std::pair<const TemplateArgument *, unsigned> Innermost
1085 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001086 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001087 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1088 Innermost.first,
1089 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001090 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001091 } else if (isFriend && D->isThisDeclarationADefinition()) {
1092 // TODO: should we remember this connection regardless of whether
1093 // the friend declaration provided a body?
1094 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001095 }
Douglas Gregora735b202009-10-13 14:39:41 +00001096
Douglas Gregore53060f2009-06-25 22:08:12 +00001097 if (InitFunctionInstantiation(Function, D))
1098 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregore53060f2009-06-25 22:08:12 +00001100 bool Redeclaration = false;
1101 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001102 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001103
John McCall68263142009-11-18 22:49:29 +00001104 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1105 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1106
John McCallaf2094e2010-04-08 09:05:18 +00001107 if (DependentFunctionTemplateSpecializationInfo *Info
1108 = D->getDependentSpecializationInfo()) {
1109 assert(isFriend && "non-friend has dependent specialization info?");
1110
1111 // This needs to be set now for future sanity.
1112 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1113
1114 // Instantiate the explicit template arguments.
1115 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1116 Info->getRAngleLoc());
1117 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1118 TemplateArgumentLoc Loc;
1119 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1120 return 0;
1121
1122 ExplicitArgs.addArgument(Loc);
1123 }
1124
1125 // Map the candidate templates to their instantiations.
1126 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1127 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1128 Info->getTemplate(I),
1129 TemplateArgs);
1130 if (!Temp) return 0;
1131
1132 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1133 }
1134
1135 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1136 &ExplicitArgs,
1137 Previous))
1138 Function->setInvalidDecl();
1139
1140 isExplicitSpecialization = true;
1141
1142 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001143 // Look only into the namespace where the friend would be declared to
1144 // find a previous declaration. This is the innermost enclosing namespace,
1145 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001146 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001147
Douglas Gregora735b202009-10-13 14:39:41 +00001148 // In C++, the previous declaration we find might be a tag type
1149 // (class or enum). In this case, the new declaration will hide the
1150 // tag type. Note that this does does not apply if we're declaring a
1151 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001152 if (Previous.isSingleTagDecl())
1153 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001154 }
1155
John McCall9f54ad42009-12-10 09:41:52 +00001156 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001157 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001158 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001159
John McCall76d32642010-04-24 01:30:58 +00001160 NamedDecl *PrincipalDecl = (TemplateParams
1161 ? cast<NamedDecl>(FunctionTemplate)
1162 : Function);
1163
Douglas Gregora735b202009-10-13 14:39:41 +00001164 // If the original function was part of a friend declaration,
1165 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001166 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001167 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001168 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001169 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001170 else
Douglas Gregora735b202009-10-13 14:39:41 +00001171 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001172
1173 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1174 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001175
1176 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1177 D->isThisDeclarationADefinition()) {
1178 // Check for a function body.
1179 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001180 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001181 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1182 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1183 << Function->getDeclName();
1184 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1185 Function->setInvalidDecl();
1186 }
1187 // Check for redefinitions due to other instantiations of this or
1188 // a similar friend function.
1189 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1190 REnd = Function->redecls_end();
1191 R != REnd; ++R) {
1192 if (*R != Function &&
1193 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1194 if (const FunctionDecl *RPattern
1195 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001196 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001197 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1198 << Function->getDeclName();
1199 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1200 Function->setInvalidDecl();
1201 break;
1202 }
1203 }
1204 }
1205 }
1206
Douglas Gregora735b202009-10-13 14:39:41 +00001207 }
1208
John McCall76d32642010-04-24 01:30:58 +00001209 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1210 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1211 PrincipalDecl->setNonMemberOperator();
1212
Douglas Gregore53060f2009-06-25 22:08:12 +00001213 return Function;
1214}
1215
Douglas Gregord60e1052009-08-27 16:57:43 +00001216Decl *
1217TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1218 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001219 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1220 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001221 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 // We are creating a function template specialization from a function
1223 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001224 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001225 llvm::FoldingSetNodeID ID;
Douglas Gregor24bae922010-07-08 18:37:38 +00001226 std::pair<const TemplateArgument *, unsigned> Innermost
1227 = TemplateArgs.getInnermost();
1228 FunctionTemplateSpecializationInfo::Profile(ID, Innermost.first,
1229 Innermost.second,
Douglas Gregor6b906862009-08-21 00:16:32 +00001230 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
1232 FunctionTemplateSpecializationInfo *Info
1233 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001234 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregor6b906862009-08-21 00:16:32 +00001236 // If we already have a function template specialization, return it.
1237 if (Info)
1238 return Info->Function;
1239 }
1240
John McCallb0cb0222010-03-27 05:57:59 +00001241 bool isFriend;
1242 if (FunctionTemplate)
1243 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1244 else
1245 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1246
Douglas Gregor79c22782010-01-16 20:21:20 +00001247 bool MergeWithParentScope = (TemplateParams != 0) ||
1248 !(isa<Decl>(Owner) &&
1249 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1250 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001251
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001252 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001253 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1254 TInfo = SubstFunctionType(D, Params);
1255 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001256 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001257 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001258
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001259 // \brief If the type of this function is not *directly* a function
1260 // type, then we're instantiating the a function that was declared
1261 // via a typedef, e.g.,
1262 //
1263 // typedef int functype(int, int);
1264 // functype func;
1265 //
1266 // In this case, we'll just go instantiate the ParmVarDecls that we
1267 // synthesized in the method declaration.
1268 if (!isa<FunctionProtoType>(T)) {
1269 assert(!Params.size() && "Instantiating type could not yield parameters");
1270 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1271 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1272 TemplateArgs);
1273 if (!P)
1274 return 0;
1275
1276 Params.push_back(P);
1277 }
1278 }
1279
John McCallb0cb0222010-03-27 05:57:59 +00001280 NestedNameSpecifier *Qualifier = D->getQualifier();
1281 if (Qualifier) {
1282 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1283 D->getQualifierRange(),
1284 TemplateArgs);
1285 if (!Qualifier) return 0;
1286 }
1287
1288 DeclContext *DC = Owner;
1289 if (isFriend) {
1290 if (Qualifier) {
1291 CXXScopeSpec SS;
1292 SS.setScopeRep(Qualifier);
1293 SS.setRange(D->getQualifierRange());
1294 DC = SemaRef.computeDeclContext(SS);
1295 } else {
1296 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1297 D->getDeclContext(),
1298 TemplateArgs);
1299 }
1300 if (!DC) return 0;
1301 }
1302
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001303 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001304 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001305 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Douglas Gregordec06662009-08-21 18:42:58 +00001307 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001308 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001309 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1310 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1311 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001312 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1313 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001314 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001315 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001316 Constructor->isInlineSpecified(),
1317 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001318 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1319 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1320 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1321 SemaRef.Context.getCanonicalType(ClassTy));
1322 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1323 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001324 T, Destructor->isInlineSpecified(),
1325 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001326 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001327 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001328 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001329 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001330 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1331 ConvTy);
1332 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1333 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001334 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001335 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001336 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001337 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001338 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001339 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001340 D->isStatic(),
1341 D->getStorageClassAsWritten(),
1342 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001343 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001344
John McCallb0cb0222010-03-27 05:57:59 +00001345 if (Qualifier)
1346 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001347
Douglas Gregord60e1052009-08-27 16:57:43 +00001348 if (TemplateParams) {
1349 // Our resulting instantiation is actually a function template, since we
1350 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001351 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001352 // template<typename T>
1353 // struct X {
1354 // template<typename U> void f(T, U);
1355 // };
1356 //
1357 // X<int> x;
1358 //
1359 // We are instantiating the member template "f" within X<int>, which means
1360 // substituting int for T, but leaving "f" as a member function template.
1361 // Build the function template itself.
1362 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1363 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001364 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001365 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001366 if (isFriend) {
1367 FunctionTemplate->setLexicalDeclContext(Owner);
1368 FunctionTemplate->setObjectOfFriendDecl(true);
1369 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001370 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001371 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001372 } else if (FunctionTemplate) {
1373 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001374 std::pair<const TemplateArgument *, unsigned> Innermost
1375 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001376 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001377 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1378 Innermost.first,
1379 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001380 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001381 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001382 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001383 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001384 }
1385
Mike Stump1eb44332009-09-09 15:08:12 +00001386 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001387 // out-of-line, the instantiation will have the same lexical
1388 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001389 if (isFriend) {
1390 Method->setLexicalDeclContext(Owner);
1391 Method->setObjectOfFriendDecl(true);
1392 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001393 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregor5545e162009-03-24 00:38:23 +00001395 // Attach the parameters
1396 for (unsigned P = 0; P < Params.size(); ++P)
1397 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001398 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001399
1400 if (InitMethodInstantiation(Method, D))
1401 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001402
John McCall68263142009-11-18 22:49:29 +00001403 LookupResult Previous(SemaRef, Name, SourceLocation(),
1404 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
John McCallb0cb0222010-03-27 05:57:59 +00001406 if (!FunctionTemplate || TemplateParams || isFriend) {
1407 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Douglas Gregordec06662009-08-21 18:42:58 +00001409 // In C++, the previous declaration we find might be a tag type
1410 // (class or enum). In this case, the new declaration will hide the
1411 // tag type. Note that this does does not apply if we're declaring a
1412 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001413 if (Previous.isSingleTagDecl())
1414 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001415 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001416
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001417 bool Redeclaration = false;
1418 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001419 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001420 /*FIXME:*/OverloadableAttrRequired);
1421
Douglas Gregor4ba31362009-12-01 17:24:26 +00001422 if (D->isPure())
1423 SemaRef.CheckPureMethod(Method, SourceRange());
1424
John McCall46460a62010-01-20 21:53:11 +00001425 Method->setAccess(D->getAccess());
1426
John McCallb0cb0222010-03-27 05:57:59 +00001427 if (FunctionTemplate) {
1428 // If there's a function template, let our caller handle it.
1429 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1430 // Don't hide a (potentially) valid declaration with an invalid one.
1431 } else {
1432 NamedDecl *DeclToAdd = (TemplateParams
1433 ? cast<NamedDecl>(FunctionTemplate)
1434 : Method);
1435 if (isFriend)
1436 Record->makeDeclVisibleInContext(DeclToAdd);
1437 else
1438 Owner->addDecl(DeclToAdd);
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001441 return Method;
1442}
1443
Douglas Gregor615c5d42009-03-24 16:43:20 +00001444Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001445 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001446}
1447
Douglas Gregor03b2b072009-03-24 00:15:49 +00001448Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001449 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001450}
1451
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001452Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001453 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001454}
1455
Douglas Gregor6477b692009-03-25 15:04:13 +00001456ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001457 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001458}
1459
John McCalle29ba202009-08-20 01:44:21 +00001460Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1461 TemplateTypeParmDecl *D) {
1462 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001463 const Type* T = D->getTypeForDecl();
1464 assert(T->isTemplateTypeParmType());
1465 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCalle29ba202009-08-20 01:44:21 +00001467 TemplateTypeParmDecl *Inst =
1468 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001469 TTPT->getDepth() - 1, TTPT->getIndex(),
1470 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001471 D->wasDeclaredWithTypename(),
1472 D->isParameterPack());
1473
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001474 if (D->hasDefaultArgument())
1475 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001476
Douglas Gregor550d9b22009-10-31 17:21:17 +00001477 // Introduce this template parameter's instantiation into the instantiation
1478 // scope.
1479 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1480
John McCalle29ba202009-08-20 01:44:21 +00001481 return Inst;
1482}
1483
Douglas Gregor33642df2009-10-23 23:25:44 +00001484Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1485 NonTypeTemplateParmDecl *D) {
1486 // Substitute into the type of the non-type template parameter.
1487 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001488 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001489 if (DI) {
1490 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1491 D->getDeclName());
1492 if (DI) T = DI->getType();
1493 } else {
1494 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1495 D->getDeclName());
1496 DI = 0;
1497 }
1498 if (T.isNull())
1499 return 0;
1500
1501 // Check that this type is acceptable for a non-type template parameter.
1502 bool Invalid = false;
1503 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1504 if (T.isNull()) {
1505 T = SemaRef.Context.IntTy;
1506 Invalid = true;
1507 }
1508
1509 NonTypeTemplateParmDecl *Param
1510 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1511 D->getDepth() - 1, D->getPosition(),
1512 D->getIdentifier(), T, DI);
1513 if (Invalid)
1514 Param->setInvalidDecl();
1515
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001516 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001517
1518 // Introduce this template parameter's instantiation into the instantiation
1519 // scope.
1520 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001521 return Param;
1522}
1523
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001524Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001525TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1526 TemplateTemplateParmDecl *D) {
1527 // Instantiate the template parameter list of the template template parameter.
1528 TemplateParameterList *TempParams = D->getTemplateParameters();
1529 TemplateParameterList *InstParams;
1530 {
1531 // Perform the actual substitution of template parameters within a new,
1532 // local instantiation scope.
1533 Sema::LocalInstantiationScope Scope(SemaRef);
1534 InstParams = SubstTemplateParams(TempParams);
1535 if (!InstParams)
1536 return NULL;
1537 }
1538
1539 // Build the template template parameter.
1540 TemplateTemplateParmDecl *Param
1541 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1542 D->getDepth() - 1, D->getPosition(),
1543 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001544 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001545
Douglas Gregor9106ef72009-11-11 16:58:32 +00001546 // Introduce this template parameter's instantiation into the instantiation
1547 // scope.
1548 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1549
1550 return Param;
1551}
1552
Douglas Gregor48c32a72009-11-17 06:07:40 +00001553Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1554 // Using directives are never dependent, so they require no explicit
1555
1556 UsingDirectiveDecl *Inst
1557 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1558 D->getNamespaceKeyLocation(),
1559 D->getQualifierRange(), D->getQualifier(),
1560 D->getIdentLocation(),
1561 D->getNominatedNamespace(),
1562 D->getCommonAncestor());
1563 Owner->addDecl(Inst);
1564 return Inst;
1565}
1566
John McCalled976492009-12-04 22:46:56 +00001567Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1568 // The nested name specifier is non-dependent, so no transformation
1569 // is required.
1570
John McCall9f54ad42009-12-10 09:41:52 +00001571 // We only need to do redeclaration lookups if we're in a class
1572 // scope (in fact, it's not really even possible in non-class
1573 // scopes).
1574 bool CheckRedeclaration = Owner->isRecord();
1575
1576 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1577 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1578
John McCalled976492009-12-04 22:46:56 +00001579 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1580 D->getLocation(),
1581 D->getNestedNameRange(),
1582 D->getUsingLocation(),
1583 D->getTargetNestedNameDecl(),
1584 D->getDeclName(),
1585 D->isTypeName());
1586
1587 CXXScopeSpec SS;
1588 SS.setScopeRep(D->getTargetNestedNameDecl());
1589 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001590
1591 if (CheckRedeclaration) {
1592 Prev.setHideTags(false);
1593 SemaRef.LookupQualifiedName(Prev, Owner);
1594
1595 // Check for invalid redeclarations.
1596 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1597 D->isTypeName(), SS,
1598 D->getLocation(), Prev))
1599 NewUD->setInvalidDecl();
1600
1601 }
1602
1603 if (!NewUD->isInvalidDecl() &&
1604 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001605 D->getLocation()))
1606 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001607
John McCalled976492009-12-04 22:46:56 +00001608 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1609 NewUD->setAccess(D->getAccess());
1610 Owner->addDecl(NewUD);
1611
John McCall9f54ad42009-12-10 09:41:52 +00001612 // Don't process the shadow decls for an invalid decl.
1613 if (NewUD->isInvalidDecl())
1614 return NewUD;
1615
John McCall323c3102009-12-22 22:26:37 +00001616 bool isFunctionScope = Owner->isFunctionOrMethod();
1617
John McCall9f54ad42009-12-10 09:41:52 +00001618 // Process the shadow decls.
1619 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1620 I != E; ++I) {
1621 UsingShadowDecl *Shadow = *I;
1622 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001623 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1624 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001625 TemplateArgs));
1626
1627 if (CheckRedeclaration &&
1628 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1629 continue;
1630
1631 UsingShadowDecl *InstShadow
1632 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1633 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001634
1635 if (isFunctionScope)
1636 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001637 }
John McCalled976492009-12-04 22:46:56 +00001638
1639 return NewUD;
1640}
1641
1642Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001643 // Ignore these; we handle them in bulk when processing the UsingDecl.
1644 return 0;
John McCalled976492009-12-04 22:46:56 +00001645}
1646
John McCall7ba107a2009-11-18 02:36:19 +00001647Decl * TemplateDeclInstantiator
1648 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001649 NestedNameSpecifier *NNS =
1650 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1651 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001652 TemplateArgs);
1653 if (!NNS)
1654 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001656 CXXScopeSpec SS;
1657 SS.setRange(D->getTargetNestedNameRange());
1658 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
1660 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001661 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001662 D->getUsingLoc(), SS, D->getLocation(),
1663 D->getDeclName(), 0,
1664 /*instantiation*/ true,
1665 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001666 if (UD)
John McCalled976492009-12-04 22:46:56 +00001667 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1668
John McCall7ba107a2009-11-18 02:36:19 +00001669 return UD;
1670}
1671
1672Decl * TemplateDeclInstantiator
1673 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1674 NestedNameSpecifier *NNS =
1675 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1676 D->getTargetNestedNameRange(),
1677 TemplateArgs);
1678 if (!NNS)
1679 return 0;
1680
1681 CXXScopeSpec SS;
1682 SS.setRange(D->getTargetNestedNameRange());
1683 SS.setScopeRep(NNS);
1684
1685 NamedDecl *UD =
1686 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1687 D->getUsingLoc(), SS, D->getLocation(),
1688 D->getDeclName(), 0,
1689 /*instantiation*/ true,
1690 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001691 if (UD)
John McCalled976492009-12-04 22:46:56 +00001692 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1693
Anders Carlsson0d8df782009-08-29 19:37:28 +00001694 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001695}
1696
John McCallce3ff2b2009-08-25 22:02:44 +00001697Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001698 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001699 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001700 if (D->isInvalidDecl())
1701 return 0;
1702
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001703 return Instantiator.Visit(D);
1704}
1705
John McCalle29ba202009-08-20 01:44:21 +00001706/// \brief Instantiates a nested template parameter list in the current
1707/// instantiation context.
1708///
1709/// \param L The parameter list to instantiate
1710///
1711/// \returns NULL if there was an error
1712TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001713TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001714 // Get errors for all the parameters before bailing out.
1715 bool Invalid = false;
1716
1717 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001718 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001719 ParamVector Params;
1720 Params.reserve(N);
1721 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1722 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001723 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001724 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001725 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001726 }
1727
1728 // Clean up if we had an error.
1729 if (Invalid) {
1730 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1731 PI != PE; ++PI)
1732 if (*PI)
1733 (*PI)->Destroy(SemaRef.Context);
1734 return NULL;
1735 }
1736
1737 TemplateParameterList *InstL
1738 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1739 L->getLAngleLoc(), &Params.front(), N,
1740 L->getRAngleLoc());
1741 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001742}
John McCalle29ba202009-08-20 01:44:21 +00001743
Douglas Gregored9c0f92009-10-29 00:04:11 +00001744/// \brief Instantiate the declaration of a class template partial
1745/// specialization.
1746///
1747/// \param ClassTemplate the (instantiated) class template that is partially
1748// specialized by the instantiation of \p PartialSpec.
1749///
1750/// \param PartialSpec the (uninstantiated) class template partial
1751/// specialization that we are instantiating.
1752///
1753/// \returns true if there was an error, false otherwise.
1754bool
1755TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1756 ClassTemplateDecl *ClassTemplate,
1757 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001758 // Create a local instantiation scope for this class template partial
1759 // specialization, which will contain the instantiations of the template
1760 // parameters.
1761 Sema::LocalInstantiationScope Scope(SemaRef);
1762
Douglas Gregored9c0f92009-10-29 00:04:11 +00001763 // Substitute into the template parameters of the class template partial
1764 // specialization.
1765 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1766 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1767 if (!InstParams)
1768 return true;
1769
1770 // Substitute into the template arguments of the class template partial
1771 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001772 const TemplateArgumentLoc *PartialSpecTemplateArgs
1773 = PartialSpec->getTemplateArgsAsWritten();
1774 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1775
John McCalld5532b62009-11-23 01:53:49 +00001776 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001777 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001778 TemplateArgumentLoc Loc;
1779 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001780 return true;
John McCalld5532b62009-11-23 01:53:49 +00001781 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001782 }
1783
1784
1785 // Check that the template argument list is well-formed for this
1786 // class template.
1787 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1788 InstTemplateArgs.size());
1789 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1790 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001791 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001792 false,
1793 Converted))
1794 return true;
1795
1796 // Figure out where to insert this class template partial specialization
1797 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001798 void *InsertPos = 0;
1799 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001800 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1801 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001802
1803 // Build the canonical type that describes the converted template
1804 // arguments of the class template partial specialization.
1805 QualType CanonType
1806 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1807 Converted.getFlatArguments(),
1808 Converted.flatSize());
1809
1810 // Build the fully-sugared type for this class template
1811 // specialization as the user wrote in the specialization
1812 // itself. This means that we'll pretty-print the type retrieved
1813 // from the specialization's declaration the way that the user
1814 // actually wrote the specialization, rather than formatting the
1815 // name based on the "canonical" representation used to store the
1816 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001817 TypeSourceInfo *WrittenTy
1818 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1819 TemplateName(ClassTemplate),
1820 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001821 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001822 CanonType);
1823
1824 if (PrevDecl) {
1825 // We've already seen a partial specialization with the same template
1826 // parameters and template arguments. This can happen, for example, when
1827 // substituting the outer template arguments ends up causing two
1828 // class template partial specializations of a member class template
1829 // to have identical forms, e.g.,
1830 //
1831 // template<typename T, typename U>
1832 // struct Outer {
1833 // template<typename X, typename Y> struct Inner;
1834 // template<typename Y> struct Inner<T, Y>;
1835 // template<typename Y> struct Inner<U, Y>;
1836 // };
1837 //
1838 // Outer<int, int> outer; // error: the partial specializations of Inner
1839 // // have the same signature.
1840 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1841 << WrittenTy;
1842 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1843 << SemaRef.Context.getTypeDeclType(PrevDecl);
1844 return true;
1845 }
1846
1847
1848 // Create the class template partial specialization declaration.
1849 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001850 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1851 PartialSpec->getTagKind(),
1852 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001853 PartialSpec->getLocation(),
1854 InstParams,
1855 ClassTemplate,
1856 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001857 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001858 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001859 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001860 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001861 // Substitute the nested name specifier, if any.
1862 if (SubstQualifier(PartialSpec, InstPartialSpec))
1863 return 0;
1864
Douglas Gregored9c0f92009-10-29 00:04:11 +00001865 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001866 InstPartialSpec->setTypeAsWritten(WrittenTy);
1867
Douglas Gregored9c0f92009-10-29 00:04:11 +00001868 // Add this partial specialization to the set of class template partial
1869 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001870 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001871 return false;
1872}
1873
John McCall21ef0fa2010-03-11 09:03:00 +00001874TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001875TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001876 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001877 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1878 assert(OldTInfo && "substituting function without type source info");
1879 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001880 TypeSourceInfo *NewTInfo
1881 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1882 D->getTypeSpecStartLoc(),
1883 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001884 if (!NewTInfo)
1885 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001886
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001887 if (NewTInfo != OldTInfo) {
1888 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001889 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001890 if (FunctionProtoTypeLoc *OldProtoLoc
1891 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1892 TypeLoc NewTL = NewTInfo->getTypeLoc();
1893 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1894 assert(NewProtoLoc && "Missing prototype?");
1895 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1896 // FIXME: Variadic templates will break this.
1897 Params.push_back(NewProtoLoc->getArg(i));
1898 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001899 OldProtoLoc->getArg(i),
1900 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001901 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001902 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001903 } else {
1904 // The function type itself was not dependent and therefore no
1905 // substitution occurred. However, we still need to instantiate
1906 // the function parameters themselves.
1907 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001908 if (FunctionProtoTypeLoc *OldProtoLoc
1909 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1910 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1911 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1912 if (!Parm)
1913 return 0;
1914 Params.push_back(Parm);
1915 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001916 }
1917 }
John McCall21ef0fa2010-03-11 09:03:00 +00001918 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001919}
1920
Mike Stump1eb44332009-09-09 15:08:12 +00001921/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001922/// declaration (New) from the corresponding fields of its template (Tmpl).
1923///
1924/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001925bool
1926TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001927 FunctionDecl *Tmpl) {
1928 if (Tmpl->isDeleted())
1929 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Douglas Gregorcca9e962009-07-01 22:01:06 +00001931 // If we are performing substituting explicitly-specified template arguments
1932 // or deduced template arguments into a function template and we reach this
1933 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001934 // to keeping the new function template specialization. We therefore
1935 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001936 // into a template instantiation for this specific function template
1937 // specialization, which is not a SFINAE context, so that we diagnose any
1938 // further errors in the declaration itself.
1939 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1940 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1941 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1942 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001943 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001944 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001945 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001946 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001947 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001948 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1949 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001950 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001951 }
1952 }
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001954 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1955 assert(Proto && "Function template without prototype?");
1956
1957 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1958 Proto->getNoReturnAttr()) {
1959 // The function has an exception specification or a "noreturn"
1960 // attribute. Substitute into each of the exception types.
1961 llvm::SmallVector<QualType, 4> Exceptions;
1962 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1963 // FIXME: Poor location information!
1964 QualType T
1965 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1966 New->getLocation(), New->getDeclName());
1967 if (T.isNull() ||
1968 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1969 continue;
1970
1971 Exceptions.push_back(T);
1972 }
1973
1974 // Rebuild the function type
1975
1976 const FunctionProtoType *NewProto
1977 = New->getType()->getAs<FunctionProtoType>();
1978 assert(NewProto && "Template instantiation without function prototype?");
1979 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1980 NewProto->arg_type_begin(),
1981 NewProto->getNumArgs(),
1982 NewProto->isVariadic(),
1983 NewProto->getTypeQuals(),
1984 Proto->hasExceptionSpec(),
1985 Proto->hasAnyExceptionSpec(),
1986 Exceptions.size(),
1987 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001988 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001989 }
1990
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001991 InstantiateAttrs(Tmpl, New);
1992
Douglas Gregore53060f2009-06-25 22:08:12 +00001993 return false;
1994}
1995
Douglas Gregor5545e162009-03-24 00:38:23 +00001996/// \brief Initializes common fields of an instantiated method
1997/// declaration (New) from the corresponding fields of its template
1998/// (Tmpl).
1999///
2000/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002001bool
2002TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002003 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002004 if (InitFunctionInstantiation(New, Tmpl))
2005 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Douglas Gregor5545e162009-03-24 00:38:23 +00002007 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
2008 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002009 if (Tmpl->isVirtualAsWritten())
2010 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00002011
2012 // FIXME: attributes
2013 // FIXME: New needs a pointer to Tmpl
2014 return false;
2015}
Douglas Gregora58861f2009-05-13 20:28:22 +00002016
2017/// \brief Instantiate the definition of the given function from its
2018/// template.
2019///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002020/// \param PointOfInstantiation the point at which the instantiation was
2021/// required. Note that this is not precisely a "point of instantiation"
2022/// for the function, but it's close.
2023///
Douglas Gregora58861f2009-05-13 20:28:22 +00002024/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002025/// function template specialization or member function of a class template
2026/// specialization.
2027///
2028/// \param Recursive if true, recursively instantiates any functions that
2029/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002030///
2031/// \param DefinitionRequired if true, then we are performing an explicit
2032/// instantiation where the body of the function is required. Complain if
2033/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002034void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002035 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002036 bool Recursive,
2037 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002038 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002039 return;
2040
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002041 // Never instantiate an explicit specialization.
2042 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2043 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002044
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002045 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002046 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002047 Stmt *Pattern = 0;
2048 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002049 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002050
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002051 if (!Pattern) {
2052 if (DefinitionRequired) {
2053 if (Function->getPrimaryTemplate())
2054 Diag(PointOfInstantiation,
2055 diag::err_explicit_instantiation_undefined_func_template)
2056 << Function->getPrimaryTemplate();
2057 else
2058 Diag(PointOfInstantiation,
2059 diag::err_explicit_instantiation_undefined_member)
2060 << 1 << Function->getDeclName() << Function->getDeclContext();
2061
2062 if (PatternDecl)
2063 Diag(PatternDecl->getLocation(),
2064 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002065 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002066 }
2067
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002068 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002069 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002070
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002071 // C++0x [temp.explicit]p9:
2072 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002073 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002074 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002075 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002076 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002077 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002078 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002080 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2081 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002082 return;
2083
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002084 // If we're performing recursive template instantiation, create our own
2085 // queue of pending implicit instantiations that we will instantiate later,
2086 // while we're still within our own instantiation context.
2087 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2088 if (Recursive)
2089 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor9679caf2010-05-12 17:27:19 +00002091 EnterExpressionEvaluationContext EvalContext(*this,
2092 Action::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002093 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2094
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002095 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002096 // recorded, unless we're actually a member function within a local
2097 // class, in which case we need to merge our results with the parent
2098 // scope (of the enclosing function).
2099 bool MergeWithParentScope = false;
2100 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2101 MergeWithParentScope = Rec->isLocalClass();
2102
2103 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002105 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002106 // instantiation scope, and set the parameter names to those used
2107 // in the template.
2108 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2109 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2110 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2111 FunctionParam->setDeclName(PatternParam->getDeclName());
2112 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2113 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002114
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002115 // Enter the scope of this instantiation. We don't use
2116 // PushDeclContext because we don't have a scope.
2117 DeclContext *PreviousContext = CurContext;
2118 CurContext = Function;
2119
Mike Stump1eb44332009-09-09 15:08:12 +00002120 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002121 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002122
2123 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002124 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002125 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2126 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2127 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002128 }
2129
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002130 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002131 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002132
Douglas Gregor52604ab2009-09-11 21:19:12 +00002133 if (Body.isInvalid())
2134 Function->setInvalidDecl();
2135
Mike Stump1eb44332009-09-09 15:08:12 +00002136 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002137 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002138
John McCall0c01d182010-03-24 05:22:00 +00002139 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2140
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002141 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002142
2143 DeclGroupRef DG(Function);
2144 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Douglas Gregor60406be2010-01-16 22:29:39 +00002146 // This class may have local implicit instantiations that need to be
2147 // instantiation within this scope.
2148 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2149 Scope.Exit();
2150
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002151 if (Recursive) {
2152 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002153 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002154 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002156 // Restore the set of pending implicit instantiations.
2157 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2158 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002159}
2160
2161/// \brief Instantiate the definition of the given variable from its
2162/// template.
2163///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002164/// \param PointOfInstantiation the point at which the instantiation was
2165/// required. Note that this is not precisely a "point of instantiation"
2166/// for the function, but it's close.
2167///
2168/// \param Var the already-instantiated declaration of a static member
2169/// variable of a class template specialization.
2170///
2171/// \param Recursive if true, recursively instantiates any functions that
2172/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002173///
2174/// \param DefinitionRequired if true, then we are performing an explicit
2175/// instantiation where an out-of-line definition of the member variable
2176/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002177void Sema::InstantiateStaticDataMemberDefinition(
2178 SourceLocation PointOfInstantiation,
2179 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002180 bool Recursive,
2181 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002182 if (Var->isInvalidDecl())
2183 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Douglas Gregor7caa6822009-07-24 20:34:43 +00002185 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002186 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002187 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002188 assert(Def->isStaticDataMember() && "Not a static data member?");
2189 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Douglas Gregor0d035142009-10-27 18:42:08 +00002191 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002192 // We did not find an out-of-line definition of this static data member,
2193 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002194 // instantiate this definition (or provide a specialization for it) in
2195 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002196 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002197 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002198 Diag(PointOfInstantiation,
2199 diag::err_explicit_instantiation_undefined_member)
2200 << 2 << Var->getDeclName() << Var->getDeclContext();
2201 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2202 }
2203
Douglas Gregor7caa6822009-07-24 20:34:43 +00002204 return;
2205 }
2206
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002207 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002208 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002209 return;
2210
2211 // C++0x [temp.explicit]p9:
2212 // Except for inline functions, other explicit instantiation declarations
2213 // have the effect of suppressing the implicit instantiation of the entity
2214 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002215 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002216 == TSK_ExplicitInstantiationDeclaration)
2217 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Douglas Gregor7caa6822009-07-24 20:34:43 +00002219 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2220 if (Inst)
2221 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Douglas Gregor7caa6822009-07-24 20:34:43 +00002223 // If we're performing recursive template instantiation, create our own
2224 // queue of pending implicit instantiations that we will instantiate later,
2225 // while we're still within our own instantiation context.
2226 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2227 if (Recursive)
2228 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregor7caa6822009-07-24 20:34:43 +00002230 // Enter the scope of this instantiation. We don't use
2231 // PushDeclContext because we don't have a scope.
2232 DeclContext *PreviousContext = CurContext;
2233 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002235 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002236 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002237 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002238 CurContext = PreviousContext;
2239
2240 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002241 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2242 assert(MSInfo && "Missing member specialization information?");
2243 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2244 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002245 DeclGroupRef DG(Var);
2246 Consumer.HandleTopLevelDecl(DG);
2247 }
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregor7caa6822009-07-24 20:34:43 +00002249 if (Recursive) {
2250 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002251 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002252 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Douglas Gregor7caa6822009-07-24 20:34:43 +00002254 // Restore the set of pending implicit instantiations.
2255 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002256 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002257}
Douglas Gregor815215d2009-05-27 05:35:12 +00002258
Anders Carlsson09025312009-08-29 05:16:22 +00002259void
2260Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2261 const CXXConstructorDecl *Tmpl,
2262 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Anders Carlsson09025312009-08-29 05:16:22 +00002264 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002265 bool AnyErrors = false;
2266
Anders Carlsson09025312009-08-29 05:16:22 +00002267 // Instantiate all the initializers.
2268 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002269 InitsEnd = Tmpl->init_end();
2270 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002271 CXXBaseOrMemberInitializer *Init = *Inits;
2272
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002273 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002274 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002275 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002277 // Instantiate the initializer.
2278 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2279 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2280 AnyErrors = true;
2281 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002282 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002283
Anders Carlsson09025312009-08-29 05:16:22 +00002284 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002285 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002286 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002287 TemplateArgs,
2288 Init->getSourceLocation(),
2289 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002290 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002291 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002292 New->setInvalidDecl();
2293 continue;
2294 }
2295
John McCalla93c9342009-12-07 02:54:59 +00002296 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002297 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002298 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002299 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002300 Init->getRParenLoc(),
2301 New->getParent());
2302 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002303 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002305 // Is this an anonymous union?
2306 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002307 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2308 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002309 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002310 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2311 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002312 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002313
2314 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002315 NewArgs.size(),
2316 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002317 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002318 Init->getRParenLoc());
2319 }
2320
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002321 if (NewInit.isInvalid()) {
2322 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002323 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002325 // FIXME: It would be nice if ASTOwningVector had a release function.
2326 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Anders Carlsson09025312009-08-29 05:16:22 +00002328 NewInits.push_back((MemInitTy *)NewInit.get());
2329 }
2330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Anders Carlsson09025312009-08-29 05:16:22 +00002332 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002333 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002334 /*FIXME: ColonLoc */
2335 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002336 NewInits.data(), NewInits.size(),
2337 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002338}
2339
John McCall52a575a2009-08-29 08:11:13 +00002340// TODO: this could be templated if the various decl types used the
2341// same method name.
2342static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2343 ClassTemplateDecl *Instance) {
2344 Pattern = Pattern->getCanonicalDecl();
2345
2346 do {
2347 Instance = Instance->getCanonicalDecl();
2348 if (Pattern == Instance) return true;
2349 Instance = Instance->getInstantiatedFromMemberTemplate();
2350 } while (Instance);
2351
2352 return false;
2353}
2354
Douglas Gregor0d696532009-09-28 06:34:35 +00002355static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2356 FunctionTemplateDecl *Instance) {
2357 Pattern = Pattern->getCanonicalDecl();
2358
2359 do {
2360 Instance = Instance->getCanonicalDecl();
2361 if (Pattern == Instance) return true;
2362 Instance = Instance->getInstantiatedFromMemberTemplate();
2363 } while (Instance);
2364
2365 return false;
2366}
2367
Douglas Gregored9c0f92009-10-29 00:04:11 +00002368static bool
2369isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2370 ClassTemplatePartialSpecializationDecl *Instance) {
2371 Pattern
2372 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2373 do {
2374 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2375 Instance->getCanonicalDecl());
2376 if (Pattern == Instance)
2377 return true;
2378 Instance = Instance->getInstantiatedFromMember();
2379 } while (Instance);
2380
2381 return false;
2382}
2383
John McCall52a575a2009-08-29 08:11:13 +00002384static bool isInstantiationOf(CXXRecordDecl *Pattern,
2385 CXXRecordDecl *Instance) {
2386 Pattern = Pattern->getCanonicalDecl();
2387
2388 do {
2389 Instance = Instance->getCanonicalDecl();
2390 if (Pattern == Instance) return true;
2391 Instance = Instance->getInstantiatedFromMemberClass();
2392 } while (Instance);
2393
2394 return false;
2395}
2396
2397static bool isInstantiationOf(FunctionDecl *Pattern,
2398 FunctionDecl *Instance) {
2399 Pattern = Pattern->getCanonicalDecl();
2400
2401 do {
2402 Instance = Instance->getCanonicalDecl();
2403 if (Pattern == Instance) return true;
2404 Instance = Instance->getInstantiatedFromMemberFunction();
2405 } while (Instance);
2406
2407 return false;
2408}
2409
2410static bool isInstantiationOf(EnumDecl *Pattern,
2411 EnumDecl *Instance) {
2412 Pattern = Pattern->getCanonicalDecl();
2413
2414 do {
2415 Instance = Instance->getCanonicalDecl();
2416 if (Pattern == Instance) return true;
2417 Instance = Instance->getInstantiatedFromMemberEnum();
2418 } while (Instance);
2419
2420 return false;
2421}
2422
John McCalled976492009-12-04 22:46:56 +00002423static bool isInstantiationOf(UsingShadowDecl *Pattern,
2424 UsingShadowDecl *Instance,
2425 ASTContext &C) {
2426 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2427}
2428
2429static bool isInstantiationOf(UsingDecl *Pattern,
2430 UsingDecl *Instance,
2431 ASTContext &C) {
2432 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2433}
2434
John McCall7ba107a2009-11-18 02:36:19 +00002435static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2436 UsingDecl *Instance,
2437 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002438 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002439}
2440
2441static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002442 UsingDecl *Instance,
2443 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002444 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002445}
2446
John McCall52a575a2009-08-29 08:11:13 +00002447static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2448 VarDecl *Instance) {
2449 assert(Instance->isStaticDataMember());
2450
2451 Pattern = Pattern->getCanonicalDecl();
2452
2453 do {
2454 Instance = Instance->getCanonicalDecl();
2455 if (Pattern == Instance) return true;
2456 Instance = Instance->getInstantiatedFromStaticDataMember();
2457 } while (Instance);
2458
2459 return false;
2460}
2461
John McCalled976492009-12-04 22:46:56 +00002462// Other is the prospective instantiation
2463// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002464static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002465 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002466 if (UnresolvedUsingTypenameDecl *UUD
2467 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2468 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2469 return isInstantiationOf(UUD, UD, Ctx);
2470 }
2471 }
2472
2473 if (UnresolvedUsingValueDecl *UUD
2474 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002475 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2476 return isInstantiationOf(UUD, UD, Ctx);
2477 }
2478 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002479
Anders Carlsson0d8df782009-08-29 19:37:28 +00002480 return false;
2481 }
Mike Stump1eb44332009-09-09 15:08:12 +00002482
John McCall52a575a2009-08-29 08:11:13 +00002483 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2484 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002485
John McCall52a575a2009-08-29 08:11:13 +00002486 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2487 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002488
John McCall52a575a2009-08-29 08:11:13 +00002489 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2490 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002491
Douglas Gregor7caa6822009-07-24 20:34:43 +00002492 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002493 if (Var->isStaticDataMember())
2494 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2495
2496 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2497 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002498
Douglas Gregor0d696532009-09-28 06:34:35 +00002499 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2500 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2501
Douglas Gregored9c0f92009-10-29 00:04:11 +00002502 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2503 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2504 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2505 PartialSpec);
2506
Anders Carlssond8b285f2009-09-01 04:26:58 +00002507 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2508 if (!Field->getDeclName()) {
2509 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002510 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002511 cast<FieldDecl>(D);
2512 }
2513 }
Mike Stump1eb44332009-09-09 15:08:12 +00002514
John McCalled976492009-12-04 22:46:56 +00002515 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2516 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2517
2518 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2519 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2520
Douglas Gregor815215d2009-05-27 05:35:12 +00002521 return D->getDeclName() && isa<NamedDecl>(Other) &&
2522 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2523}
2524
2525template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002526static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002527 NamedDecl *D,
2528 ForwardIterator first,
2529 ForwardIterator last) {
2530 for (; first != last; ++first)
2531 if (isInstantiationOf(Ctx, D, *first))
2532 return cast<NamedDecl>(*first);
2533
2534 return 0;
2535}
2536
John McCall02cace72009-08-28 07:59:38 +00002537/// \brief Finds the instantiation of the given declaration context
2538/// within the current instantiation.
2539///
2540/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002541DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002542 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002543 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002544 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002545 return cast_or_null<DeclContext>(ID);
2546 } else return DC;
2547}
2548
Douglas Gregored961e72009-05-27 17:54:46 +00002549/// \brief Find the instantiation of the given declaration within the
2550/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002551///
2552/// This routine is intended to be used when \p D is a declaration
2553/// referenced from within a template, that needs to mapped into the
2554/// corresponding declaration within an instantiation. For example,
2555/// given:
2556///
2557/// \code
2558/// template<typename T>
2559/// struct X {
2560/// enum Kind {
2561/// KnownValue = sizeof(T)
2562/// };
2563///
2564/// bool getKind() const { return KnownValue; }
2565/// };
2566///
2567/// template struct X<int>;
2568/// \endcode
2569///
2570/// In the instantiation of X<int>::getKind(), we need to map the
2571/// EnumConstantDecl for KnownValue (which refers to
2572/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002573/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2574/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002575NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002576 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002577 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002578 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002579 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002580 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002581 // D is a local of some kind. Look into the map of local
2582 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002583 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002584 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002585
Douglas Gregore95b4092009-09-16 18:34:49 +00002586 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2587 if (!Record->isDependentContext())
2588 return D;
2589
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002590 // If the RecordDecl is actually the injected-class-name or a
2591 // "templated" declaration for a class template, class template
2592 // partial specialization, or a member class of a class template,
2593 // substitute into the injected-class-name of the class template
2594 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002595 QualType T;
2596 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2597
2598 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002599 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002600 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2601 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002602 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002603
2604 // If we call SubstType with an InjectedClassNameType here we
2605 // can end up in an infinite loop.
2606 T = Context.getTypeDeclType(Record);
2607 assert(isa<InjectedClassNameType>(T) &&
2608 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002609 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002610 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002611
2612 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002613 // Substitute into the injected-class-name to get the type
2614 // corresponding to the instantiation we want, which may also be
2615 // the current instantiation (if we're in a template
2616 // definition). This substitution should never fail, since we
2617 // know we can instantiate the injected-class-name or we
2618 // wouldn't have gotten to the injected-class-name!
2619
2620 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2621 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002622 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2623 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2624
2625 if (!T->isDependentType()) {
2626 assert(T->isRecordType() && "Instantiation must produce a record type");
2627 return T->getAs<RecordType>()->getDecl();
2628 }
2629
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002630 // We are performing "partial" template instantiation to create
2631 // the member declarations for the members of a class template
2632 // specialization. Therefore, D is actually referring to something
2633 // in the current instantiation. Look through the current
2634 // context, which contains actual instantiations, to find the
2635 // instantiation of the "current instantiation" that D refers
2636 // to.
2637 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002638 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002639 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002640 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002641 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002642 if (isInstantiationOf(ClassTemplate,
2643 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002644 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002645
2646 if (!DC->isDependentContext())
2647 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002648 }
2649
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002650 // We're performing "instantiation" of a member of the current
2651 // instantiation while we are type-checking the
2652 // definition. Compute the declaration context and return that.
2653 assert(!SawNonDependentContext &&
2654 "No dependent context while instantiating record");
2655 DeclContext *DC = computeDeclContext(T);
2656 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002657 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002658 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002659 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002660
Douglas Gregore95b4092009-09-16 18:34:49 +00002661 // Fall through to deal with other dependent record types (e.g.,
2662 // anonymous unions in class templates).
2663 }
John McCall52a575a2009-08-29 08:11:13 +00002664
Douglas Gregore95b4092009-09-16 18:34:49 +00002665 if (!ParentDC->isDependentContext())
2666 return D;
2667
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002668 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002669 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002670 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Douglas Gregor815215d2009-05-27 05:35:12 +00002672 if (ParentDC != D->getDeclContext()) {
2673 // We performed some kind of instantiation in the parent context,
2674 // so now we need to look into the instantiated parent context to
2675 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002676
John McCall3cb0ebd2010-03-10 03:28:59 +00002677 // If our context used to be dependent, we may need to instantiate
2678 // it before performing lookup into that context.
2679 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002680 if (!Spec->isDependentContext()) {
2681 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002682 const RecordType *Tag = T->getAs<RecordType>();
2683 assert(Tag && "type of non-dependent record is not a RecordType");
2684 if (!Tag->isBeingDefined() &&
2685 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2686 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002687 }
2688 }
2689
Douglas Gregor815215d2009-05-27 05:35:12 +00002690 NamedDecl *Result = 0;
2691 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002692 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002693 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2694 } else {
2695 // Since we don't have a name for the entity we're looking for,
2696 // our only option is to walk through all of the declarations to
2697 // find that name. This will occur in a few cases:
2698 //
2699 // - anonymous struct/union within a template
2700 // - unnamed class/struct/union/enum within a template
2701 //
2702 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002703 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002704 ParentDC->decls_begin(),
2705 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002706 }
Mike Stump1eb44332009-09-09 15:08:12 +00002707
John McCall9f54ad42009-12-10 09:41:52 +00002708 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002709 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2710 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002711 && "Unable to find instantiation of declaration!");
2712
Douglas Gregor815215d2009-05-27 05:35:12 +00002713 D = Result;
2714 }
2715
Douglas Gregor815215d2009-05-27 05:35:12 +00002716 return D;
2717}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002718
Mike Stump1eb44332009-09-09 15:08:12 +00002719/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002720/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002721void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2722 while (!PendingLocalImplicitInstantiations.empty() ||
2723 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2724 PendingImplicitInstantiation Inst;
2725
2726 if (PendingLocalImplicitInstantiations.empty()) {
2727 Inst = PendingImplicitInstantiations.front();
2728 PendingImplicitInstantiations.pop_front();
2729 } else {
2730 Inst = PendingLocalImplicitInstantiations.front();
2731 PendingLocalImplicitInstantiations.pop_front();
2732 }
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Douglas Gregor7caa6822009-07-24 20:34:43 +00002734 // Instantiate function definitions
2735 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002736 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002737 Function->getLocation(), *this,
2738 Context.getSourceManager(),
2739 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002741 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002742 continue;
2743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Douglas Gregor7caa6822009-07-24 20:34:43 +00002745 // Instantiate static data member definitions.
2746 VarDecl *Var = cast<VarDecl>(Inst.first);
2747 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002748
Chandler Carruth291b4412010-02-13 10:17:50 +00002749 // Don't try to instantiate declarations if the most recent redeclaration
2750 // is invalid.
2751 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2752 continue;
2753
2754 // Check if the most recent declaration has changed the specialization kind
2755 // and removed the need for implicit instantiation.
2756 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2757 case TSK_Undeclared:
2758 assert(false && "Cannot instantitiate an undeclared specialization.");
2759 case TSK_ExplicitInstantiationDeclaration:
2760 case TSK_ExplicitInstantiationDefinition:
2761 case TSK_ExplicitSpecialization:
2762 continue; // No longer need implicit instantiation.
2763 case TSK_ImplicitInstantiation:
2764 break;
2765 }
2766
Mike Stump1eb44332009-09-09 15:08:12 +00002767 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002768 Var->getLocation(), *this,
2769 Context.getSourceManager(),
2770 "instantiating static data member "
2771 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Douglas Gregor7caa6822009-07-24 20:34:43 +00002773 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002774 }
2775}
John McCall0c01d182010-03-24 05:22:00 +00002776
2777void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2778 const MultiLevelTemplateArgumentList &TemplateArgs) {
2779 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2780 E = Pattern->ddiag_end(); I != E; ++I) {
2781 DependentDiagnostic *DD = *I;
2782
2783 switch (DD->getKind()) {
2784 case DependentDiagnostic::Access:
2785 HandleDependentAccessCheck(*DD, TemplateArgs);
2786 break;
2787 }
2788 }
2789}