blob: 11b98e0af2a1175bd9bb0d083e8761d39ee426bd [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//===----------------------------------------------------------------------===/
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallf312b1e2010-08-26 23:41:50 +000014#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000022#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
32
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35 TemplateArgs);
36
37 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000039
40 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
48
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51 TemplateArgs);
52
53 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000055
56 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
Chandler Carruth4ced79f2010-06-25 03:22:07 +000060// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +000061void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +000063 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64 i != e; ++i) {
65 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +000066 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000068 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +000069 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +000070 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +000071 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +000072
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +000074 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000075 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000076 if (!Result.isInvalid())
77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78 }
79 else {
80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000081 TemplateArgs,
82 Aligned->getLocation(),
83 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000084 if (Result)
85 AddAlignedAttr(Aligned->getLocation(), New, Result);
86 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000087 continue;
88 }
89 }
90
Anders Carlssond8fe2d52009-11-07 06:07:58 +000091 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +000092 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000093 New->addAttr(NewAttr);
94 }
95}
96
Douglas Gregor4f722be2009-03-25 15:45:12 +000097Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
99 assert(false && "Translation units cannot be instantiated");
100 return D;
101}
102
103Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000104TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
105 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
106 D->getIdentifier());
107 Owner->addDecl(Inst);
108 return Inst;
109}
110
111Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000112TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
113 assert(false && "Namespaces cannot be instantiated");
114 return D;
115}
116
John McCall3dbd3d52010-02-16 06:53:13 +0000117Decl *
118TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
119 NamespaceAliasDecl *Inst
120 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
121 D->getNamespaceLoc(),
122 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000123 D->getIdentifier(),
124 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000125 D->getTargetNameLoc(),
126 D->getNamespace());
127 Owner->addDecl(Inst);
128 return Inst;
129}
130
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000131Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
132 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000133 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000134 if (DI->getType()->isDependentType() ||
135 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000136 DI = SemaRef.SubstType(DI, TemplateArgs,
137 D->getLocation(), D->getDeclName());
138 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000140 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000141 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000142 } else {
143 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000144 }
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000146 // Create the new typedef
147 TypedefDecl *Typedef
Abramo Bagnara344577e2011-03-06 15:48:19 +0000148 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
149 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000150 if (Invalid)
151 Typedef->setInvalidDecl();
152
John McCallcde5a402011-02-01 08:20:08 +0000153 // If the old typedef was the name for linkage purposes of an anonymous
154 // tag decl, re-establish that relationship for the new typedef.
155 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
156 TagDecl *oldTag = oldTagType->getDecl();
157 if (oldTag->getTypedefForAnonDecl() == D) {
158 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
159 assert(!newTag->getIdentifier() && !newTag->getTypedefForAnonDecl());
160 newTag->setTypedefForAnonDecl(Typedef);
161 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000162 }
163
John McCall5126fd02009-12-30 00:31:22 +0000164 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000165 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
166 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000167 if (!InstPrev)
168 return 0;
169
John McCall5126fd02009-12-30 00:31:22 +0000170 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
171 }
172
John McCall1d8d1cc2010-08-01 02:01:53 +0000173 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000174
John McCall46460a62010-01-20 21:53:11 +0000175 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000176 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000178 return Typedef;
179}
180
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000181/// \brief Instantiate an initializer, breaking it into separate
182/// initialization arguments.
183///
184/// \param S The semantic analysis object.
185///
186/// \param Init The initializer to instantiate.
187///
188/// \param TemplateArgs Template arguments to be substituted into the
189/// initializer.
190///
191/// \param NewArgs Will be filled in with the instantiation arguments.
192///
193/// \returns true if an error occurred, false otherwise
194static bool InstantiateInitializer(Sema &S, Expr *Init,
195 const MultiLevelTemplateArgumentList &TemplateArgs,
196 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000197 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000198 SourceLocation &RParenLoc) {
199 NewArgs.clear();
200 LParenLoc = SourceLocation();
201 RParenLoc = SourceLocation();
202
203 if (!Init)
204 return false;
205
John McCall4765fa02010-12-06 08:20:24 +0000206 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000207 Init = ExprTemp->getSubExpr();
208
209 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
210 Init = Binder->getSubExpr();
211
212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
213 Init = ICE->getSubExprAsWritten();
214
215 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
216 LParenLoc = ParenList->getLParenLoc();
217 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000218 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
219 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000220 }
221
222 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000223 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000224 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
225 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000226 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000227
Douglas Gregor28329e52010-03-24 21:22:47 +0000228 // FIXME: Fake locations!
229 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000230 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000231 return false;
232 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000233 }
234
John McCall60d7b3a2010-08-24 06:29:42 +0000235 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000236 if (Result.isInvalid())
237 return true;
238
239 NewArgs.push_back(Result.takeAs<Expr>());
240 return false;
241}
242
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000243Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000244 // If this is the variable for an anonymous struct or union,
245 // instantiate the anonymous struct/union type first.
246 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
247 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
248 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
249 return 0;
250
John McCallce3ff2b2009-08-25 22:02:44 +0000251 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000252 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000253 TemplateArgs,
254 D->getTypeSpecStartLoc(),
255 D->getDeclName());
256 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000257 return 0;
258
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000259 if (DI->getType()->isFunctionType()) {
260 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
261 << D->isStaticDataMember() << DI->getType();
262 return 0;
263 }
264
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000265 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000266 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000267 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000268 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000269 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000270 D->getStorageClass(),
271 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000272 Var->setThreadSpecified(D->isThreadSpecified());
273 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000274 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000275
John McCallb6217662010-03-15 10:12:16 +0000276 // Substitute the nested name specifier, if any.
277 if (SubstQualifier(D, Var))
278 return 0;
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000281 // out-of-line, the instantiation will have the same lexical
282 // context (which will be a namespace scope) as the template.
283 if (D->isOutOfLine())
284 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000285
John McCall46460a62010-01-20 21:53:11 +0000286 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000287
288 if (!D->isStaticDataMember())
289 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000290
Mike Stump390b4cc2009-05-16 07:39:55 +0000291 // FIXME: In theory, we could have a previous declaration for variables that
292 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000293 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000294 // FIXME: having to fake up a LookupResult is dumb.
295 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000296 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000297 if (D->isStaticDataMember())
298 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000299 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Douglas Gregor7caa6822009-07-24 20:34:43 +0000301 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000302 if (!D->isStaticDataMember())
303 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000304 Owner->makeDeclVisibleInContext(Var);
305 } else {
306 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000307 if (Owner->isFunctionOrMethod())
308 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000309 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000310 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000311
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000312 // Link instantiations of static data members back to the template from
313 // which they were instantiated.
314 if (Var->isStaticDataMember())
315 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000316 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000317
Douglas Gregor60c93c92010-02-09 07:26:29 +0000318 if (Var->getAnyInitializer()) {
319 // We already have an initializer in the class.
320 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000321 if (Var->isStaticDataMember() && !D->isOutOfLine())
322 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
323 else
324 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
325
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000326 // Instantiate the initializer.
327 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000328 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000329 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000330 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000331 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000332 // Attach the initializer to the declaration, if we have one.
333 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000334 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000335 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000336 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000337 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000338 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000339 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000340 RParenLoc,
341 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000342 } else {
343 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000344 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000345 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000346 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000347 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000348 // FIXME: Not too happy about invalidating the declaration
349 // because of a bogus initializer.
350 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000351 }
352
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000353 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000354 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
355 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000356 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000357
Douglas Gregor5764f612010-05-08 23:05:03 +0000358 // Diagnose unused local variables.
359 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
360 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000361
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000362 return Var;
363}
364
Abramo Bagnara6206d532010-06-05 05:09:32 +0000365Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
366 AccessSpecDecl* AD
367 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
368 D->getAccessSpecifierLoc(), D->getColonLoc());
369 Owner->addHiddenDecl(AD);
370 return AD;
371}
372
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000373Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
374 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000375 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000376 if (DI->getType()->isDependentType() ||
377 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000378 DI = SemaRef.SubstType(DI, TemplateArgs,
379 D->getLocation(), D->getDeclName());
380 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000381 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000382 Invalid = true;
383 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000384 // C++ [temp.arg.type]p3:
385 // If a declaration acquires a function type through a type
386 // dependent on a template-parameter and this causes a
387 // declaration that does not use the syntactic form of a
388 // function declarator to have function type, the program is
389 // ill-formed.
390 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000391 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000392 Invalid = true;
393 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000394 } else {
395 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000396 }
397
398 Expr *BitWidth = D->getBitWidth();
399 if (Invalid)
400 BitWidth = 0;
401 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000402 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000403 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
John McCall60d7b3a2010-08-24 06:29:42 +0000405 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000406 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407 if (InstantiatedBitWidth.isInvalid()) {
408 Invalid = true;
409 BitWidth = 0;
410 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000411 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000412 }
413
John McCall07fb6be2009-10-22 23:33:21 +0000414 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
415 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000416 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000417 D->getLocation(),
418 D->isMutable(),
419 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000420 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 D->getAccess(),
422 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000423 if (!Field) {
424 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000425 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
John McCall1d8d1cc2010-08-01 02:01:53 +0000428 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000429
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000430 if (Invalid)
431 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000433 if (!Field->getDeclName()) {
434 // Keep track of where this decl came from.
435 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000436 }
437 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
438 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000439 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000440 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000443 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000444 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000445 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000446
447 return Field;
448}
449
Francois Pichet87c2e122010-11-21 06:08:52 +0000450Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
451 NamedDecl **NamedChain =
452 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
453
454 int i = 0;
455 for (IndirectFieldDecl::chain_iterator PI =
456 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000457 PI != PE; ++PI) {
458 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
459 TemplateArgs);
460 if (!Next)
461 return 0;
462
463 NamedChain[i++] = Next;
464 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000465
Francois Pichet40e17752010-12-09 10:07:54 +0000466 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000467 IndirectFieldDecl* IndirectField
468 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000469 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000470 NamedChain, D->getChainingSize());
471
472
473 IndirectField->setImplicit(D->isImplicit());
474 IndirectField->setAccess(D->getAccess());
475 Owner->addDecl(IndirectField);
476 return IndirectField;
477}
478
John McCall02cace72009-08-28 07:59:38 +0000479Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000480 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000481 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000482 if (TypeSourceInfo *Ty = D->getFriendType()) {
483 TypeSourceInfo *InstTy =
484 SemaRef.SubstType(Ty, TemplateArgs,
485 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000486 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000487 return 0;
John McCall02cace72009-08-28 07:59:38 +0000488
Douglas Gregor06245bf2010-04-07 17:57:12 +0000489 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
490 if (!FD)
491 return 0;
492
493 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000494 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000495 Owner->addDecl(FD);
496 return FD;
497 }
498
499 NamedDecl *ND = D->getFriendDecl();
500 assert(ND && "friend decl must be a decl or a type!");
501
John McCallaf2094e2010-04-08 09:05:18 +0000502 // All of the Visit implementations for the various potential friend
503 // declarations have to be carefully written to work for friend
504 // objects, with the most important detail being that the target
505 // decl should almost certainly not be placed in Owner.
506 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000507 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000508
John McCall02cace72009-08-28 07:59:38 +0000509 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000510 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
511 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000512 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000513 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000514 Owner->addDecl(FD);
515 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000516}
517
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000518Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
519 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregorac7610d2009-06-22 20:57:11 +0000521 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000522 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000523
John McCall60d7b3a2010-08-24 06:29:42 +0000524 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000525 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000526 if (InstantiatedAssertExpr.isInvalid())
527 return 0;
528
John McCall60d7b3a2010-08-24 06:29:42 +0000529 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000530 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000531 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000532 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000533 Message.get(),
534 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535}
536
537Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000538 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000539 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000540 /*PrevDecl=*/0, D->isScoped(),
541 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000542 if (D->isFixed()) {
543 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
544 // If we have type source information for the underlying type, it means it
545 // has been explicitly set by the user. Perform substitution on it before
546 // moving on.
547 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
548 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
549 TemplateArgs,
550 UnderlyingLoc,
551 DeclarationName()));
552
553 if (!Enum->getIntegerTypeSourceInfo())
554 Enum->setIntegerType(SemaRef.Context.IntTy);
555 }
556 else {
557 assert(!D->getIntegerType()->isDependentType()
558 && "Dependent type without type source info");
559 Enum->setIntegerType(D->getIntegerType());
560 }
561 }
562
John McCall5b629aa2010-10-22 23:36:17 +0000563 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
564
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000565 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000566 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000567 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000568 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000569 Enum->startDefinition();
570
Douglas Gregor96084f12010-03-01 19:00:07 +0000571 if (D->getDeclContext()->isFunctionOrMethod())
572 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
573
John McCalld226f652010-08-21 09:40:31 +0000574 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000575
576 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000577 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
578 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579 EC != ECEnd; ++EC) {
580 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000581 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000582 if (Expr *UninstValue = EC->getInitExpr()) {
583 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000584 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000585 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
John McCallce3ff2b2009-08-25 22:02:44 +0000587 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000588 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000589
590 // Drop the initial value and continue.
591 bool isInvalid = false;
592 if (Value.isInvalid()) {
593 Value = SemaRef.Owned((Expr *)0);
594 isInvalid = true;
595 }
596
Mike Stump1eb44332009-09-09 15:08:12 +0000597 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000598 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
599 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000600 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000601
602 if (isInvalid) {
603 if (EnumConst)
604 EnumConst->setInvalidDecl();
605 Enum->setInvalidDecl();
606 }
607
608 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000609 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
610
John McCall3b85ecf2010-01-23 22:37:59 +0000611 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000612 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000613 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000614 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000615
616 if (D->getDeclContext()->isFunctionOrMethod()) {
617 // If the enumeration is within a function or method, record the enum
618 // constant as a local.
619 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
620 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000621 }
622 }
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000624 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000625 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000626 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000627 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000628 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000629 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000630
631 return Enum;
632}
633
Douglas Gregor6477b692009-03-25 15:04:13 +0000634Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
635 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
636 return 0;
637}
638
John McCalle29ba202009-08-20 01:44:21 +0000639Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000640 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
641
Douglas Gregor550d9b22009-10-31 17:21:17 +0000642 // Create a local instantiation scope for this class template, which
643 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000644 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000645 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000646 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000647 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000648 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000649
650 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000651
652 // Instantiate the qualifier. We have to do this first in case
653 // we're a friend declaration, because if we are then we need to put
654 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000655 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
656 if (QualifierLoc) {
657 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
658 TemplateArgs);
659 if (!QualifierLoc)
660 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000661 }
662
663 CXXRecordDecl *PrevDecl = 0;
664 ClassTemplateDecl *PrevClassTemplate = 0;
665
Nick Lewycky37574f52010-11-08 23:29:42 +0000666 if (!isFriend && Pattern->getPreviousDeclaration()) {
667 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
668 if (Found.first != Found.second) {
669 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
670 if (PrevClassTemplate)
671 PrevDecl = PrevClassTemplate->getTemplatedDecl();
672 }
673 }
674
John McCall93ba8572010-03-25 06:39:04 +0000675 // If this isn't a friend, then it's a member template, in which
676 // case we just want to build the instantiation in the
677 // specialization. If it is a friend, we want to build it in
678 // the appropriate context.
679 DeclContext *DC = Owner;
680 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000681 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000682 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000683 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000684 DC = SemaRef.computeDeclContext(SS);
685 if (!DC) return 0;
686 } else {
687 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
688 Pattern->getDeclContext(),
689 TemplateArgs);
690 }
691
692 // Look for a previous declaration of the template in the owning
693 // context.
694 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
695 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
696 SemaRef.LookupQualifiedName(R, DC);
697
698 if (R.isSingleResult()) {
699 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
700 if (PrevClassTemplate)
701 PrevDecl = PrevClassTemplate->getTemplatedDecl();
702 }
703
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000704 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000705 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000706 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000707 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000708 return 0;
709 }
710
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000711 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000712 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000713 bool Complain = true;
714
715 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
716 // template for struct std::tr1::__detail::_Map_base, where the
717 // template parameters of the friend declaration don't match the
718 // template parameters of the original declaration. In this one
719 // case, we don't complain about the ill-formed friend
720 // declaration.
721 if (isFriend && Pattern->getIdentifier() &&
722 Pattern->getIdentifier()->isStr("_Map_base") &&
723 DC->isNamespace() &&
724 cast<NamespaceDecl>(DC)->getIdentifier() &&
725 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
726 DeclContext *DCParent = DC->getParent();
727 if (DCParent->isNamespace() &&
728 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
729 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
730 DeclContext *DCParent2 = DCParent->getParent();
731 if (DCParent2->isNamespace() &&
732 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
733 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
734 DCParent2->getParent()->isTranslationUnit())
735 Complain = false;
736 }
737 }
738
John McCall93ba8572010-03-25 06:39:04 +0000739 TemplateParameterList *PrevParams
740 = PrevClassTemplate->getTemplateParameters();
741
742 // Make sure the parameter lists match.
743 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000744 Complain,
745 Sema::TPL_TemplateMatch)) {
746 if (Complain)
747 return 0;
748
749 AdoptedPreviousTemplateParams = true;
750 InstParams = PrevParams;
751 }
John McCall93ba8572010-03-25 06:39:04 +0000752
753 // Do some additional validation, then merge default arguments
754 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000755 if (!AdoptedPreviousTemplateParams &&
756 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000757 Sema::TPC_ClassTemplate))
758 return 0;
759 }
760 }
761
John McCalle29ba202009-08-20 01:44:21 +0000762 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000763 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000764 Pattern->getLocStart(), Pattern->getLocation(),
765 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000766 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000767
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000768 if (QualifierLoc)
769 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000770
John McCalle29ba202009-08-20 01:44:21 +0000771 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000772 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
773 D->getIdentifier(), InstParams, RecordInst,
774 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000775 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000776
John McCall93ba8572010-03-25 06:39:04 +0000777 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000778 if (PrevClassTemplate)
779 Inst->setAccess(PrevClassTemplate->getAccess());
780 else
781 Inst->setAccess(D->getAccess());
782
John McCall93ba8572010-03-25 06:39:04 +0000783 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
784 // TODO: do we want to track the instantiation progeny of this
785 // friend target decl?
786 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000787 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000788 if (!PrevClassTemplate)
789 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000790 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000791
792 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000793 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000794 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000795
Douglas Gregor259571e2009-10-30 22:42:42 +0000796 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000797 if (isFriend) {
798 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000799 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000800 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000801
John McCalle29ba202009-08-20 01:44:21 +0000802 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000803
804 if (!PrevClassTemplate) {
805 // Queue up any out-of-line partial specializations of this member
806 // class template; the client will force their instantiation once
807 // the enclosing class has been instantiated.
808 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
809 D->getPartialSpecializations(PartialSpecs);
810 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
811 if (PartialSpecs[I]->isOutOfLine())
812 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
813 }
814
John McCalle29ba202009-08-20 01:44:21 +0000815 return Inst;
816}
817
Douglas Gregord60e1052009-08-27 16:57:43 +0000818Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000819TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
820 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000821 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
822
823 // Lookup the already-instantiated declaration in the instantiation
824 // of the class template and return that.
825 DeclContext::lookup_result Found
826 = Owner->lookup(ClassTemplate->getDeclName());
827 if (Found.first == Found.second)
828 return 0;
829
830 ClassTemplateDecl *InstClassTemplate
831 = dyn_cast<ClassTemplateDecl>(*Found.first);
832 if (!InstClassTemplate)
833 return 0;
834
Douglas Gregord65587f2010-11-10 19:44:59 +0000835 if (ClassTemplatePartialSpecializationDecl *Result
836 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
837 return Result;
838
839 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000840}
841
842Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000843TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000844 // Create a local instantiation scope for this function template, which
845 // will contain the instantiations of the template parameters and then get
846 // merged with the local instantiation scope for the function template
847 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000848 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 TemplateParameterList *TempParams = D->getTemplateParameters();
851 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000852 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000853 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000854
Douglas Gregora735b202009-10-13 14:39:41 +0000855 FunctionDecl *Instantiated = 0;
856 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
857 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
858 InstParams));
859 else
860 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
861 D->getTemplatedDecl(),
862 InstParams));
863
864 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000865 return 0;
866
John McCall46460a62010-01-20 21:53:11 +0000867 Instantiated->setAccess(D->getAccess());
868
Mike Stump1eb44332009-09-09 15:08:12 +0000869 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000871 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000872 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000873 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000874 assert(InstTemplate &&
875 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000876
John McCallb1a56e72010-03-26 23:10:15 +0000877 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
878
John McCalle976ffe2009-12-14 23:19:40 +0000879 // Link the instantiation back to the pattern *unless* this is a
880 // non-definition friend declaration.
881 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000882 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000883 InstTemplate->setInstantiatedFromMemberTemplate(D);
884
John McCallb1a56e72010-03-26 23:10:15 +0000885 // Make declarations visible in the appropriate context.
886 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000887 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000888
Douglas Gregord60e1052009-08-27 16:57:43 +0000889 return InstTemplate;
890}
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
893 CXXRecordDecl *PrevDecl = 0;
894 if (D->isInjectedClassName())
895 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000896 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000897 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
898 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000899 TemplateArgs);
900 if (!Prev) return 0;
901 PrevDecl = cast<CXXRecordDecl>(Prev);
902 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000903
904 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000905 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000906 D->getLocStart(), D->getLocation(),
907 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000908
909 // Substitute the nested name specifier, if any.
910 if (SubstQualifier(D, Record))
911 return 0;
912
Douglas Gregord475b8d2009-03-25 21:17:03 +0000913 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000914 // FIXME: Check against AS_none is an ugly hack to work around the issue that
915 // the tag decls introduced by friend class declarations don't have an access
916 // specifier. Remove once this area of the code gets sorted out.
917 if (D->getAccess() != AS_none)
918 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000919 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000920 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000921
John McCall02cace72009-08-28 07:59:38 +0000922 // If the original function was part of a friend declaration,
923 // inherit its namespace state.
924 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
925 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
926
Douglas Gregor9901c572010-05-21 00:31:19 +0000927 // Make sure that anonymous structs and unions are recorded.
928 if (D->isAnonymousStructOrUnion()) {
929 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000930 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000931 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
932 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000933
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000934 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000935 return Record;
936}
937
John McCall02cace72009-08-28 07:59:38 +0000938/// Normal class members are of more specific types and therefore
939/// don't make it here. This function serves two purposes:
940/// 1) instantiating function templates
941/// 2) substituting friend declarations
942/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000943Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000944 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000945 // Check whether there is already a function template specialization for
946 // this declaration.
947 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
948 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000949 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000950 std::pair<const TemplateArgument *, unsigned> Innermost
951 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000953 FunctionDecl *SpecFunc
954 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
955 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregor127102b2009-06-29 20:59:39 +0000957 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000958 if (SpecFunc)
959 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
John McCallb0cb0222010-03-27 05:57:59 +0000962 bool isFriend;
963 if (FunctionTemplate)
964 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
965 else
966 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
967
Douglas Gregor79c22782010-01-16 20:21:20 +0000968 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000969 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000970 !(isa<Decl>(Owner) &&
971 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000972 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregore53060f2009-06-25 22:08:12 +0000974 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000975 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
976 TInfo = SubstFunctionType(D, Params);
977 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000978 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000979 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000980
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000981 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
982 if (QualifierLoc) {
983 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
984 TemplateArgs);
985 if (!QualifierLoc)
986 return 0;
John McCalld325daa2010-03-26 04:53:08 +0000987 }
988
John McCall68b6b872010-02-06 01:50:47 +0000989 // If we're instantiating a local function declaration, put the result
990 // in the owner; otherwise we need to find the instantiated context.
991 DeclContext *DC;
992 if (D->getDeclContext()->isFunctionOrMethod())
993 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000994 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +0000995 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000996 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +0000997 DC = SemaRef.computeDeclContext(SS);
998 if (!DC) return 0;
999 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001000 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1001 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001002 }
John McCall68b6b872010-02-06 01:50:47 +00001003
John McCall02cace72009-08-28 07:59:38 +00001004 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001005 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1006 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001007 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001008 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001009
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001010 if (QualifierLoc)
1011 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001012
John McCallb1a56e72010-03-26 23:10:15 +00001013 DeclContext *LexicalDC = Owner;
1014 if (!isFriend && D->isOutOfLine()) {
1015 assert(D->getDeclContext()->isFileContext());
1016 LexicalDC = D->getDeclContext();
1017 }
1018
1019 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregore53060f2009-06-25 22:08:12 +00001021 // Attach the parameters
1022 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001023 if (Params[P])
1024 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001025 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001026
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001027 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001028 if (TemplateParams) {
1029 // Our resulting instantiation is actually a function template, since we
1030 // are substituting only the outer template parameters. For example, given
1031 //
1032 // template<typename T>
1033 // struct X {
1034 // template<typename U> friend void f(T, U);
1035 // };
1036 //
1037 // X<int> x;
1038 //
1039 // We are instantiating the friend function template "f" within X<int>,
1040 // which means substituting int for T, but leaving "f" as a friend function
1041 // template.
1042 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001043 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001044 Function->getLocation(),
1045 Function->getDeclName(),
1046 TemplateParams, Function);
1047 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001048
1049 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001050
1051 if (isFriend && D->isThisDeclarationADefinition()) {
1052 // TODO: should we remember this connection regardless of whether
1053 // the friend declaration provided a body?
1054 FunctionTemplate->setInstantiatedFromMemberTemplate(
1055 D->getDescribedFunctionTemplate());
1056 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001057 } else if (FunctionTemplate) {
1058 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001059 std::pair<const TemplateArgument *, unsigned> Innermost
1060 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001061 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001062 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001063 Innermost.first,
1064 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001065 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001066 } else if (isFriend && D->isThisDeclarationADefinition()) {
1067 // TODO: should we remember this connection regardless of whether
1068 // the friend declaration provided a body?
1069 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001070 }
Douglas Gregora735b202009-10-13 14:39:41 +00001071
Douglas Gregore53060f2009-06-25 22:08:12 +00001072 if (InitFunctionInstantiation(Function, D))
1073 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Douglas Gregore53060f2009-06-25 22:08:12 +00001075 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001076 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001077
John McCall68263142009-11-18 22:49:29 +00001078 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1079 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1080
John McCallaf2094e2010-04-08 09:05:18 +00001081 if (DependentFunctionTemplateSpecializationInfo *Info
1082 = D->getDependentSpecializationInfo()) {
1083 assert(isFriend && "non-friend has dependent specialization info?");
1084
1085 // This needs to be set now for future sanity.
1086 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1087
1088 // Instantiate the explicit template arguments.
1089 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1090 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001091 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1092 ExplicitArgs, TemplateArgs))
1093 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001094
1095 // Map the candidate templates to their instantiations.
1096 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1097 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1098 Info->getTemplate(I),
1099 TemplateArgs);
1100 if (!Temp) return 0;
1101
1102 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1103 }
1104
1105 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1106 &ExplicitArgs,
1107 Previous))
1108 Function->setInvalidDecl();
1109
1110 isExplicitSpecialization = true;
1111
1112 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001113 // Look only into the namespace where the friend would be declared to
1114 // find a previous declaration. This is the innermost enclosing namespace,
1115 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001116 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001117
Douglas Gregora735b202009-10-13 14:39:41 +00001118 // In C++, the previous declaration we find might be a tag type
1119 // (class or enum). In this case, the new declaration will hide the
1120 // tag type. Note that this does does not apply if we're declaring a
1121 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001122 if (Previous.isSingleTagDecl())
1123 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001124 }
1125
John McCall9f54ad42009-12-10 09:41:52 +00001126 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001127 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001128
John McCall76d32642010-04-24 01:30:58 +00001129 NamedDecl *PrincipalDecl = (TemplateParams
1130 ? cast<NamedDecl>(FunctionTemplate)
1131 : Function);
1132
Douglas Gregora735b202009-10-13 14:39:41 +00001133 // If the original function was part of a friend declaration,
1134 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001135 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001136 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001137 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001138 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001139 else
Douglas Gregora735b202009-10-13 14:39:41 +00001140 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001141
1142 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1143 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001144
Gabor Greif77535df2010-08-30 22:25:56 +00001145 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001146
Douglas Gregor238058c2010-05-18 05:45:02 +00001147 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1148 D->isThisDeclarationADefinition()) {
1149 // Check for a function body.
1150 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001151 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001152 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1153 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1154 << Function->getDeclName();
1155 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1156 Function->setInvalidDecl();
1157 }
1158 // Check for redefinitions due to other instantiations of this or
1159 // a similar friend function.
1160 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1161 REnd = Function->redecls_end();
1162 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001163 if (*R == Function)
1164 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001165 switch (R->getFriendObjectKind()) {
1166 case Decl::FOK_None:
1167 if (!queuedInstantiation && R->isUsed(false)) {
1168 if (MemberSpecializationInfo *MSInfo
1169 = Function->getMemberSpecializationInfo()) {
1170 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1171 SourceLocation Loc = R->getLocation(); // FIXME
1172 MSInfo->setPointOfInstantiation(Loc);
1173 SemaRef.PendingLocalImplicitInstantiations.push_back(
1174 std::make_pair(Function, Loc));
1175 queuedInstantiation = true;
1176 }
1177 }
1178 }
1179 break;
1180 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001181 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001182 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001183 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001184 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1185 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001186 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001187 Function->setInvalidDecl();
1188 break;
1189 }
1190 }
1191 }
1192 }
Douglas Gregora735b202009-10-13 14:39:41 +00001193 }
1194
John McCall76d32642010-04-24 01:30:58 +00001195 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1196 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1197 PrincipalDecl->setNonMemberOperator();
1198
Douglas Gregore53060f2009-06-25 22:08:12 +00001199 return Function;
1200}
1201
Douglas Gregord60e1052009-08-27 16:57:43 +00001202Decl *
1203TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1204 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001205 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1206 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001207 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001208 // We are creating a function template specialization from a function
1209 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001210 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001211 std::pair<const TemplateArgument *, unsigned> Innermost
1212 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001214 FunctionDecl *SpecFunc
1215 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1216 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor6b906862009-08-21 00:16:32 +00001218 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001219 if (SpecFunc)
1220 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001221 }
1222
John McCallb0cb0222010-03-27 05:57:59 +00001223 bool isFriend;
1224 if (FunctionTemplate)
1225 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1226 else
1227 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1228
Douglas Gregor79c22782010-01-16 20:21:20 +00001229 bool MergeWithParentScope = (TemplateParams != 0) ||
1230 !(isa<Decl>(Owner) &&
1231 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001232 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001233
John McCall4eab39f2010-10-19 02:26:41 +00001234 // Instantiate enclosing template arguments for friends.
1235 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1236 unsigned NumTempParamLists = 0;
1237 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1238 TempParamLists.set_size(NumTempParamLists);
1239 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1240 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1241 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1242 if (!InstParams)
1243 return NULL;
1244 TempParamLists[I] = InstParams;
1245 }
1246 }
1247
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001248 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001249 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1250 TInfo = SubstFunctionType(D, Params);
1251 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001252 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001253 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001254
Abramo Bagnara723df242010-12-14 22:11:44 +00001255 // \brief If the type of this function, after ignoring parentheses,
1256 // is not *directly* a function type, then we're instantiating a function
1257 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001258 //
1259 // typedef int functype(int, int);
1260 // functype func;
1261 //
1262 // In this case, we'll just go instantiate the ParmVarDecls that we
1263 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001264 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001265 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001266 llvm::SmallVector<QualType, 4> ParamTypes;
1267 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1268 D->getNumParams(), TemplateArgs, ParamTypes,
1269 &Params))
1270 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001271 }
1272
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001273 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1274 if (QualifierLoc) {
1275 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001276 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001277 if (!QualifierLoc)
1278 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001279 }
1280
1281 DeclContext *DC = Owner;
1282 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001283 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001284 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001285 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001286 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001287
1288 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1289 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001290 } else {
1291 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1292 D->getDeclContext(),
1293 TemplateArgs);
1294 }
1295 if (!DC) return 0;
1296 }
1297
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001298 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001299 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001300 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001302 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001303 DeclarationNameInfo NameInfo
1304 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001305 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001306 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001307 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001308 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001309 Constructor->isInlineSpecified(),
1310 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001311 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001312 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001313 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001314 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001315 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001316 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001317 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001318 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001319 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001320 Conversion->isExplicit(),
1321 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001322 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001323 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001324 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001325 D->isStatic(),
1326 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001327 D->isInlineSpecified(),
1328 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001329 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001330
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001331 if (QualifierLoc)
1332 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001333
Douglas Gregord60e1052009-08-27 16:57:43 +00001334 if (TemplateParams) {
1335 // Our resulting instantiation is actually a function template, since we
1336 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001337 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001338 // template<typename T>
1339 // struct X {
1340 // template<typename U> void f(T, U);
1341 // };
1342 //
1343 // X<int> x;
1344 //
1345 // We are instantiating the member template "f" within X<int>, which means
1346 // substituting int for T, but leaving "f" as a member function template.
1347 // Build the function template itself.
1348 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1349 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001350 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001351 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001352 if (isFriend) {
1353 FunctionTemplate->setLexicalDeclContext(Owner);
1354 FunctionTemplate->setObjectOfFriendDecl(true);
1355 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001356 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001357 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001358 } else if (FunctionTemplate) {
1359 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001360 std::pair<const TemplateArgument *, unsigned> Innermost
1361 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001362 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001363 TemplateArgumentList::CreateCopy(SemaRef.Context,
1364 Innermost.first,
1365 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001366 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001367 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001368 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001369 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001370 }
1371
Mike Stump1eb44332009-09-09 15:08:12 +00001372 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001373 // out-of-line, the instantiation will have the same lexical
1374 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001375 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001376 if (NumTempParamLists)
1377 Method->setTemplateParameterListsInfo(SemaRef.Context,
1378 NumTempParamLists,
1379 TempParamLists.data());
1380
John McCallb0cb0222010-03-27 05:57:59 +00001381 Method->setLexicalDeclContext(Owner);
1382 Method->setObjectOfFriendDecl(true);
1383 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001384 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregor5545e162009-03-24 00:38:23 +00001386 // Attach the parameters
1387 for (unsigned P = 0; P < Params.size(); ++P)
1388 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001389 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001390
1391 if (InitMethodInstantiation(Method, D))
1392 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001393
Abramo Bagnara25777432010-08-11 22:01:17 +00001394 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1395 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
John McCallb0cb0222010-03-27 05:57:59 +00001397 if (!FunctionTemplate || TemplateParams || isFriend) {
1398 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Douglas Gregordec06662009-08-21 18:42:58 +00001400 // In C++, the previous declaration we find might be a tag type
1401 // (class or enum). In this case, the new declaration will hide the
1402 // tag type. Note that this does does not apply if we're declaring a
1403 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001404 if (Previous.isSingleTagDecl())
1405 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001406 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001407
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001408 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001409 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001410
Douglas Gregor4ba31362009-12-01 17:24:26 +00001411 if (D->isPure())
1412 SemaRef.CheckPureMethod(Method, SourceRange());
1413
John McCall46460a62010-01-20 21:53:11 +00001414 Method->setAccess(D->getAccess());
1415
Anders Carlsson9eefa222011-01-20 06:52:44 +00001416 SemaRef.CheckOverrideControl(Method);
1417
John McCallb0cb0222010-03-27 05:57:59 +00001418 if (FunctionTemplate) {
1419 // If there's a function template, let our caller handle it.
1420 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1421 // Don't hide a (potentially) valid declaration with an invalid one.
1422 } else {
1423 NamedDecl *DeclToAdd = (TemplateParams
1424 ? cast<NamedDecl>(FunctionTemplate)
1425 : Method);
1426 if (isFriend)
1427 Record->makeDeclVisibleInContext(DeclToAdd);
1428 else
1429 Owner->addDecl(DeclToAdd);
1430 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001431
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001432 return Method;
1433}
1434
Douglas Gregor615c5d42009-03-24 16:43:20 +00001435Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001436 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001437}
1438
Douglas Gregor03b2b072009-03-24 00:15:49 +00001439Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001440 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001441}
1442
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001443Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001444 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001445}
1446
Douglas Gregor6477b692009-03-25 15:04:13 +00001447ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001448 return SemaRef.SubstParmVarDecl(D, TemplateArgs, llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001449}
1450
John McCalle29ba202009-08-20 01:44:21 +00001451Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1452 TemplateTypeParmDecl *D) {
1453 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001454 const Type* T = D->getTypeForDecl();
1455 assert(T->isTemplateTypeParmType());
1456 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCalle29ba202009-08-20 01:44:21 +00001458 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001459 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1460 D->getLocStart(), D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001461 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001462 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001463 D->wasDeclaredWithTypename(),
1464 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001465 Inst->setAccess(AS_public);
1466
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001467 if (D->hasDefaultArgument())
1468 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001469
Douglas Gregor550d9b22009-10-31 17:21:17 +00001470 // Introduce this template parameter's instantiation into the instantiation
1471 // scope.
1472 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1473
John McCalle29ba202009-08-20 01:44:21 +00001474 return Inst;
1475}
1476
Douglas Gregor33642df2009-10-23 23:25:44 +00001477Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1478 NonTypeTemplateParmDecl *D) {
1479 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001480 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1481 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1482 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1483 bool IsExpandedParameterPack = false;
1484 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001485 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001486 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001487
1488 if (D->isExpandedParameterPack()) {
1489 // The non-type template parameter pack is an already-expanded pack
1490 // expansion of types. Substitute into each of the expanded types.
1491 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1492 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1493 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1494 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1495 TemplateArgs,
1496 D->getLocation(),
1497 D->getDeclName());
1498 if (!NewDI)
1499 return 0;
1500
1501 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1502 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1503 D->getLocation());
1504 if (NewT.isNull())
1505 return 0;
1506 ExpandedParameterPackTypes.push_back(NewT);
1507 }
1508
1509 IsExpandedParameterPack = true;
1510 DI = D->getTypeSourceInfo();
1511 T = DI->getType();
1512 } else if (isa<PackExpansionTypeLoc>(TL)) {
1513 // The non-type template parameter pack's type is a pack expansion of types.
1514 // Determine whether we need to expand this parameter pack into separate
1515 // types.
1516 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1517 TypeLoc Pattern = Expansion.getPatternLoc();
1518 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1519 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1520
1521 // Determine whether the set of unexpanded parameter packs can and should
1522 // be expanded.
1523 bool Expand = true;
1524 bool RetainExpansion = false;
1525 llvm::Optional<unsigned> OrigNumExpansions
1526 = Expansion.getTypePtr()->getNumExpansions();
1527 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1528 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1529 Pattern.getSourceRange(),
1530 Unexpanded.data(),
1531 Unexpanded.size(),
1532 TemplateArgs,
1533 Expand, RetainExpansion,
1534 NumExpansions))
1535 return 0;
1536
1537 if (Expand) {
1538 for (unsigned I = 0; I != *NumExpansions; ++I) {
1539 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1540 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1541 D->getLocation(),
1542 D->getDeclName());
1543 if (!NewDI)
1544 return 0;
1545
1546 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1547 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1548 NewDI->getType(),
1549 D->getLocation());
1550 if (NewT.isNull())
1551 return 0;
1552 ExpandedParameterPackTypes.push_back(NewT);
1553 }
1554
1555 // Note that we have an expanded parameter pack. The "type" of this
1556 // expanded parameter pack is the original expansion type, but callers
1557 // will end up using the expanded parameter pack types for type-checking.
1558 IsExpandedParameterPack = true;
1559 DI = D->getTypeSourceInfo();
1560 T = DI->getType();
1561 } else {
1562 // We cannot fully expand the pack expansion now, so substitute into the
1563 // pattern and create a new pack expansion type.
1564 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1565 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1566 D->getLocation(),
1567 D->getDeclName());
1568 if (!NewPattern)
1569 return 0;
1570
1571 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1572 NumExpansions);
1573 if (!DI)
1574 return 0;
1575
1576 T = DI->getType();
1577 }
1578 } else {
1579 // Simple case: substitution into a parameter that is not a parameter pack.
1580 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1581 D->getLocation(), D->getDeclName());
1582 if (!DI)
1583 return 0;
1584
1585 // Check that this type is acceptable for a non-type template parameter.
1586 bool Invalid = false;
1587 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1588 D->getLocation());
1589 if (T.isNull()) {
1590 T = SemaRef.Context.IntTy;
1591 Invalid = true;
1592 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001593 }
1594
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001595 NonTypeTemplateParmDecl *Param;
1596 if (IsExpandedParameterPack)
1597 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001598 D->getInnerLocStart(),
1599 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001600 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001601 D->getPosition(),
1602 D->getIdentifier(), T,
1603 DI,
1604 ExpandedParameterPackTypes.data(),
1605 ExpandedParameterPackTypes.size(),
1606 ExpandedParameterPackTypesAsWritten.data());
1607 else
1608 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001609 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001610 D->getLocation(),
1611 D->getDepth() - TemplateArgs.getNumLevels(),
1612 D->getPosition(),
1613 D->getIdentifier(), T,
1614 D->isParameterPack(), DI);
1615
Douglas Gregor9a299e02011-03-04 17:52:15 +00001616 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001617 if (Invalid)
1618 Param->setInvalidDecl();
1619
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001620 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001621
1622 // Introduce this template parameter's instantiation into the instantiation
1623 // scope.
1624 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001625 return Param;
1626}
1627
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001628Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001629TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1630 TemplateTemplateParmDecl *D) {
1631 // Instantiate the template parameter list of the template template parameter.
1632 TemplateParameterList *TempParams = D->getTemplateParameters();
1633 TemplateParameterList *InstParams;
1634 {
1635 // Perform the actual substitution of template parameters within a new,
1636 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001637 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001638 InstParams = SubstTemplateParams(TempParams);
1639 if (!InstParams)
1640 return NULL;
1641 }
1642
1643 // Build the template template parameter.
1644 TemplateTemplateParmDecl *Param
1645 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001646 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001647 D->getPosition(), D->isParameterPack(),
1648 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001649 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001650 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001651
Douglas Gregor9106ef72009-11-11 16:58:32 +00001652 // Introduce this template parameter's instantiation into the instantiation
1653 // scope.
1654 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1655
1656 return Param;
1657}
1658
Douglas Gregor48c32a72009-11-17 06:07:40 +00001659Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001660 // Using directives are never dependent (and never contain any types or
1661 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001662
1663 UsingDirectiveDecl *Inst
1664 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1665 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001666 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001667 D->getIdentLocation(),
1668 D->getNominatedNamespace(),
1669 D->getCommonAncestor());
1670 Owner->addDecl(Inst);
1671 return Inst;
1672}
1673
John McCalled976492009-12-04 22:46:56 +00001674Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001675
1676 // The nested name specifier may be dependent, for example
1677 // template <typename T> struct t {
1678 // struct s1 { T f1(); };
1679 // struct s2 : s1 { using s1::f1; };
1680 // };
1681 // template struct t<int>;
1682 // Here, in using s1::f1, s1 refers to t<T>::s1;
1683 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001684 NestedNameSpecifierLoc QualifierLoc
1685 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1686 TemplateArgs);
1687 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001688 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001689
1690 // The name info is non-dependent, so no transformation
1691 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001692 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001693
John McCall9f54ad42009-12-10 09:41:52 +00001694 // We only need to do redeclaration lookups if we're in a class
1695 // scope (in fact, it's not really even possible in non-class
1696 // scopes).
1697 bool CheckRedeclaration = Owner->isRecord();
1698
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001699 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1700 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001701
John McCalled976492009-12-04 22:46:56 +00001702 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001703 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001704 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001705 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001706 D->isTypeName());
1707
Douglas Gregor5149f372011-02-25 15:54:31 +00001708 CXXScopeSpec SS;
1709 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001710 if (CheckRedeclaration) {
1711 Prev.setHideTags(false);
1712 SemaRef.LookupQualifiedName(Prev, Owner);
1713
1714 // Check for invalid redeclarations.
1715 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1716 D->isTypeName(), SS,
1717 D->getLocation(), Prev))
1718 NewUD->setInvalidDecl();
1719
1720 }
1721
1722 if (!NewUD->isInvalidDecl() &&
1723 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001724 D->getLocation()))
1725 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001726
John McCalled976492009-12-04 22:46:56 +00001727 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1728 NewUD->setAccess(D->getAccess());
1729 Owner->addDecl(NewUD);
1730
John McCall9f54ad42009-12-10 09:41:52 +00001731 // Don't process the shadow decls for an invalid decl.
1732 if (NewUD->isInvalidDecl())
1733 return NewUD;
1734
John McCall323c3102009-12-22 22:26:37 +00001735 bool isFunctionScope = Owner->isFunctionOrMethod();
1736
John McCall9f54ad42009-12-10 09:41:52 +00001737 // Process the shadow decls.
1738 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1739 I != E; ++I) {
1740 UsingShadowDecl *Shadow = *I;
1741 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001742 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1743 Shadow->getLocation(),
1744 Shadow->getTargetDecl(),
1745 TemplateArgs));
1746 if (!InstTarget)
1747 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001748
1749 if (CheckRedeclaration &&
1750 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1751 continue;
1752
1753 UsingShadowDecl *InstShadow
1754 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1755 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001756
1757 if (isFunctionScope)
1758 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001759 }
John McCalled976492009-12-04 22:46:56 +00001760
1761 return NewUD;
1762}
1763
1764Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001765 // Ignore these; we handle them in bulk when processing the UsingDecl.
1766 return 0;
John McCalled976492009-12-04 22:46:56 +00001767}
1768
John McCall7ba107a2009-11-18 02:36:19 +00001769Decl * TemplateDeclInstantiator
1770 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001771 NestedNameSpecifierLoc QualifierLoc
1772 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1773 TemplateArgs);
1774 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001775 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001777 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001778 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001780 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1781 // Hence, no tranformation is required for it.
1782 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001783 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001784 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001785 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001786 /*instantiation*/ true,
1787 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001788 if (UD)
John McCalled976492009-12-04 22:46:56 +00001789 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1790
John McCall7ba107a2009-11-18 02:36:19 +00001791 return UD;
1792}
1793
1794Decl * TemplateDeclInstantiator
1795 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001796 NestedNameSpecifierLoc QualifierLoc
1797 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1798 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001799 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001800
John McCall7ba107a2009-11-18 02:36:19 +00001801 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001802 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001803
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001804 DeclarationNameInfo NameInfo
1805 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1806
John McCall7ba107a2009-11-18 02:36:19 +00001807 NamedDecl *UD =
1808 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001809 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001810 /*instantiation*/ true,
1811 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001812 if (UD)
John McCalled976492009-12-04 22:46:56 +00001813 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1814
Anders Carlsson0d8df782009-08-29 19:37:28 +00001815 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001816}
1817
John McCallce3ff2b2009-08-25 22:02:44 +00001818Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001819 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001820 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001821 if (D->isInvalidDecl())
1822 return 0;
1823
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001824 return Instantiator.Visit(D);
1825}
1826
John McCalle29ba202009-08-20 01:44:21 +00001827/// \brief Instantiates a nested template parameter list in the current
1828/// instantiation context.
1829///
1830/// \param L The parameter list to instantiate
1831///
1832/// \returns NULL if there was an error
1833TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001834TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001835 // Get errors for all the parameters before bailing out.
1836 bool Invalid = false;
1837
1838 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001839 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001840 ParamVector Params;
1841 Params.reserve(N);
1842 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1843 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001844 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001845 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001846 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001847 }
1848
1849 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001850 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001851 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001852
1853 TemplateParameterList *InstL
1854 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1855 L->getLAngleLoc(), &Params.front(), N,
1856 L->getRAngleLoc());
1857 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001858}
John McCalle29ba202009-08-20 01:44:21 +00001859
Douglas Gregored9c0f92009-10-29 00:04:11 +00001860/// \brief Instantiate the declaration of a class template partial
1861/// specialization.
1862///
1863/// \param ClassTemplate the (instantiated) class template that is partially
1864// specialized by the instantiation of \p PartialSpec.
1865///
1866/// \param PartialSpec the (uninstantiated) class template partial
1867/// specialization that we are instantiating.
1868///
Douglas Gregord65587f2010-11-10 19:44:59 +00001869/// \returns The instantiated partial specialization, if successful; otherwise,
1870/// NULL to indicate an error.
1871ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001872TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1873 ClassTemplateDecl *ClassTemplate,
1874 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001875 // Create a local instantiation scope for this class template partial
1876 // specialization, which will contain the instantiations of the template
1877 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001878 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001879
Douglas Gregored9c0f92009-10-29 00:04:11 +00001880 // Substitute into the template parameters of the class template partial
1881 // specialization.
1882 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1883 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1884 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001885 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001886
1887 // Substitute into the template arguments of the class template partial
1888 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001889 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001890 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1891 PartialSpec->getNumTemplateArgsAsWritten(),
1892 InstTemplateArgs, TemplateArgs))
1893 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001894
Douglas Gregored9c0f92009-10-29 00:04:11 +00001895 // Check that the template argument list is well-formed for this
1896 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001897 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001898 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1899 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001900 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001901 false,
1902 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001903 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001904
1905 // Figure out where to insert this class template partial specialization
1906 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001907 void *InsertPos = 0;
1908 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001909 = ClassTemplate->findPartialSpecialization(Converted.data(),
1910 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001911
1912 // Build the canonical type that describes the converted template
1913 // arguments of the class template partial specialization.
1914 QualType CanonType
1915 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001916 Converted.data(),
1917 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001918
1919 // Build the fully-sugared type for this class template
1920 // specialization as the user wrote in the specialization
1921 // itself. This means that we'll pretty-print the type retrieved
1922 // from the specialization's declaration the way that the user
1923 // actually wrote the specialization, rather than formatting the
1924 // name based on the "canonical" representation used to store the
1925 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001926 TypeSourceInfo *WrittenTy
1927 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1928 TemplateName(ClassTemplate),
1929 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001930 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001931 CanonType);
1932
1933 if (PrevDecl) {
1934 // We've already seen a partial specialization with the same template
1935 // parameters and template arguments. This can happen, for example, when
1936 // substituting the outer template arguments ends up causing two
1937 // class template partial specializations of a member class template
1938 // to have identical forms, e.g.,
1939 //
1940 // template<typename T, typename U>
1941 // struct Outer {
1942 // template<typename X, typename Y> struct Inner;
1943 // template<typename Y> struct Inner<T, Y>;
1944 // template<typename Y> struct Inner<U, Y>;
1945 // };
1946 //
1947 // Outer<int, int> outer; // error: the partial specializations of Inner
1948 // // have the same signature.
1949 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001950 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001951 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1952 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001953 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001954 }
1955
1956
1957 // Create the class template partial specialization declaration.
1958 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001959 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1960 PartialSpec->getTagKind(),
1961 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001962 PartialSpec->getLocStart(),
1963 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001964 InstParams,
1965 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001966 Converted.data(),
1967 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001968 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001969 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001970 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001971 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001972 // Substitute the nested name specifier, if any.
1973 if (SubstQualifier(PartialSpec, InstPartialSpec))
1974 return 0;
1975
Douglas Gregored9c0f92009-10-29 00:04:11 +00001976 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001977 InstPartialSpec->setTypeAsWritten(WrittenTy);
1978
Douglas Gregored9c0f92009-10-29 00:04:11 +00001979 // Add this partial specialization to the set of class template partial
1980 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001981 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001982 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001983}
1984
John McCall21ef0fa2010-03-11 09:03:00 +00001985TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001986TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001987 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001988 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1989 assert(OldTInfo && "substituting function without type source info");
1990 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001991 TypeSourceInfo *NewTInfo
1992 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1993 D->getTypeSpecStartLoc(),
1994 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001995 if (!NewTInfo)
1996 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001997
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001998 if (NewTInfo != OldTInfo) {
1999 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002000 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002001 if (FunctionProtoTypeLoc *OldProtoLoc
2002 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002003 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002004 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2005 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002006 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2007 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2008 OldIdx != NumOldParams; ++OldIdx) {
2009 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2010 if (!OldParam->isParameterPack() ||
2011 (NewIdx < NumNewParams &&
2012 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2013 // Simple case: normal parameter, or a parameter pack that's
2014 // instantiated to a (still-dependent) parameter pack.
2015 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2016 Params.push_back(NewParam);
2017 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2018 NewParam);
2019 continue;
2020 }
2021
2022 // Parameter pack: make the instantiation an argument pack.
2023 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2024 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002025 unsigned NumArgumentsInExpansion
2026 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2027 TemplateArgs);
2028 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002029 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2030 Params.push_back(NewParam);
2031 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2032 NewParam);
2033 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002034 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002035 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002036 } else {
2037 // The function type itself was not dependent and therefore no
2038 // substitution occurred. However, we still need to instantiate
2039 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002040 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002041 if (FunctionProtoTypeLoc *OldProtoLoc
2042 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2043 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2044 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2045 if (!Parm)
2046 return 0;
2047 Params.push_back(Parm);
2048 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002049 }
2050 }
John McCall21ef0fa2010-03-11 09:03:00 +00002051 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002052}
2053
Mike Stump1eb44332009-09-09 15:08:12 +00002054/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002055/// declaration (New) from the corresponding fields of its template (Tmpl).
2056///
2057/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002058bool
2059TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002060 FunctionDecl *Tmpl) {
2061 if (Tmpl->isDeleted())
2062 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregorcca9e962009-07-01 22:01:06 +00002064 // If we are performing substituting explicitly-specified template arguments
2065 // or deduced template arguments into a function template and we reach this
2066 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002067 // to keeping the new function template specialization. We therefore
2068 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002069 // into a template instantiation for this specific function template
2070 // specialization, which is not a SFINAE context, so that we diagnose any
2071 // further errors in the declaration itself.
2072 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2073 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2074 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2075 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002076 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002077 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002078 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002079 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002080 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002081 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2082 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002083 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002084 }
2085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002087 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2088 assert(Proto && "Function template without prototype?");
2089
Sebastian Redl60618fa2011-03-12 11:50:43 +00002090 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002091 // The function has an exception specification or a "noreturn"
2092 // attribute. Substitute into each of the exception types.
2093 llvm::SmallVector<QualType, 4> Exceptions;
2094 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2095 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002096 if (const PackExpansionType *PackExpansion
2097 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2098 // We have a pack expansion. Instantiate it.
2099 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2100 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2101 Unexpanded);
2102 assert(!Unexpanded.empty() &&
2103 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002104
Douglas Gregorb99268b2010-12-21 00:52:54 +00002105 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002106 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002107 llvm::Optional<unsigned> NumExpansions
2108 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002109 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2110 SourceRange(),
2111 Unexpanded.data(),
2112 Unexpanded.size(),
2113 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002114 Expand,
2115 RetainExpansion,
2116 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002117 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002118
Douglas Gregorb99268b2010-12-21 00:52:54 +00002119 if (!Expand) {
2120 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002121 // just substitute into the pattern and create a new pack expansion
2122 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002123 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2124 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2125 TemplateArgs,
2126 New->getLocation(), New->getDeclName());
2127 if (T.isNull())
2128 break;
2129
Douglas Gregorcded4f62011-01-14 17:04:44 +00002130 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002131 Exceptions.push_back(T);
2132 continue;
2133 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002134
Douglas Gregorb99268b2010-12-21 00:52:54 +00002135 // Substitute into the pack expansion pattern for each template
2136 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002137 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002138 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2139
2140 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2141 TemplateArgs,
2142 New->getLocation(), New->getDeclName());
2143 if (T.isNull()) {
2144 Invalid = true;
2145 break;
2146 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002147
Douglas Gregorb99268b2010-12-21 00:52:54 +00002148 Exceptions.push_back(T);
2149 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002150
Douglas Gregorb99268b2010-12-21 00:52:54 +00002151 if (Invalid)
2152 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002153
Douglas Gregorb99268b2010-12-21 00:52:54 +00002154 continue;
2155 }
2156
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002157 QualType T
2158 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2159 New->getLocation(), New->getDeclName());
2160 if (T.isNull() ||
2161 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2162 continue;
2163
2164 Exceptions.push_back(T);
2165 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002166 Expr *NoexceptExpr = 0;
2167 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2168 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2169 if (E.isUsable())
2170 NoexceptExpr = E.take();
2171 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002172
2173 // Rebuild the function type
2174
John McCalle23cf432010-12-14 08:05:40 +00002175 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002176 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002177 EPI.NumExceptions = Exceptions.size();
2178 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002179 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002180 EPI.ExtInfo = Proto->getExtInfo();
2181
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002182 const FunctionProtoType *NewProto
2183 = New->getType()->getAs<FunctionProtoType>();
2184 assert(NewProto && "Template instantiation without function prototype?");
2185 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2186 NewProto->arg_type_begin(),
2187 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002188 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002189 }
2190
John McCall1d8d1cc2010-08-01 02:01:53 +00002191 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002192
Douglas Gregore53060f2009-06-25 22:08:12 +00002193 return false;
2194}
2195
Douglas Gregor5545e162009-03-24 00:38:23 +00002196/// \brief Initializes common fields of an instantiated method
2197/// declaration (New) from the corresponding fields of its template
2198/// (Tmpl).
2199///
2200/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002201bool
2202TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002203 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002204 if (InitFunctionInstantiation(New, Tmpl))
2205 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Douglas Gregor5545e162009-03-24 00:38:23 +00002207 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002208 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002209 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002210
2211 // FIXME: attributes
2212 // FIXME: New needs a pointer to Tmpl
2213 return false;
2214}
Douglas Gregora58861f2009-05-13 20:28:22 +00002215
2216/// \brief Instantiate the definition of the given function from its
2217/// template.
2218///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002219/// \param PointOfInstantiation the point at which the instantiation was
2220/// required. Note that this is not precisely a "point of instantiation"
2221/// for the function, but it's close.
2222///
Douglas Gregora58861f2009-05-13 20:28:22 +00002223/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002224/// function template specialization or member function of a class template
2225/// specialization.
2226///
2227/// \param Recursive if true, recursively instantiates any functions that
2228/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002229///
2230/// \param DefinitionRequired if true, then we are performing an explicit
2231/// instantiation where the body of the function is required. Complain if
2232/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002233void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002234 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002235 bool Recursive,
2236 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002237 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002238 return;
2239
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002240 // Never instantiate an explicit specialization.
2241 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2242 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002243
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002244 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002245 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002246 Stmt *Pattern = 0;
2247 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002248 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002249
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002250 if (!Pattern) {
2251 if (DefinitionRequired) {
2252 if (Function->getPrimaryTemplate())
2253 Diag(PointOfInstantiation,
2254 diag::err_explicit_instantiation_undefined_func_template)
2255 << Function->getPrimaryTemplate();
2256 else
2257 Diag(PointOfInstantiation,
2258 diag::err_explicit_instantiation_undefined_member)
2259 << 1 << Function->getDeclName() << Function->getDeclContext();
2260
2261 if (PatternDecl)
2262 Diag(PatternDecl->getLocation(),
2263 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002264 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002265 } else if (Function->getTemplateSpecializationKind()
2266 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002267 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002268 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002269 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002270
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002271 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002272 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002273
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002274 // C++0x [temp.explicit]p9:
2275 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002276 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002277 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002278 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002279 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002280 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002281 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002283 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2284 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002285 return;
2286
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002287 // If we're performing recursive template instantiation, create our own
2288 // queue of pending implicit instantiations that we will instantiate later,
2289 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002290 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002291 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002292 if (Recursive) {
2293 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002294 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002295 }
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Douglas Gregor9679caf2010-05-12 17:27:19 +00002297 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002298 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002299 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002300
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002301 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002302 // recorded, unless we're actually a member function within a local
2303 // class, in which case we need to merge our results with the parent
2304 // scope (of the enclosing function).
2305 bool MergeWithParentScope = false;
2306 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2307 MergeWithParentScope = Rec->isLocalClass();
2308
2309 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002311 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002312 // instantiation scope, and set the parameter names to those used
2313 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002314 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002315 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2316 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002317 if (!PatternParam->isParameterPack()) {
2318 // Simple case: not a parameter pack.
2319 assert(FParamIdx < Function->getNumParams());
2320 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2321 FunctionParam->setDeclName(PatternParam->getDeclName());
2322 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2323 ++FParamIdx;
2324 continue;
2325 }
2326
2327 // Expand the parameter pack.
2328 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2329 for (unsigned NumFParams = Function->getNumParams();
2330 FParamIdx < NumFParams;
2331 ++FParamIdx) {
2332 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2333 FunctionParam->setDeclName(PatternParam->getDeclName());
2334 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2335 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002336 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002337
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002338 // Enter the scope of this instantiation. We don't use
2339 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002340 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002341
Mike Stump1eb44332009-09-09 15:08:12 +00002342 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002343 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002344
2345 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002346 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002347 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2348 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2349 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002350 }
2351
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002352 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002353 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002354
Douglas Gregor52604ab2009-09-11 21:19:12 +00002355 if (Body.isInvalid())
2356 Function->setInvalidDecl();
2357
John McCall9ae2f072010-08-23 23:25:46 +00002358 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002359 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002360
John McCall0c01d182010-03-24 05:22:00 +00002361 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2362
John McCalleee1d542011-02-14 07:13:47 +00002363 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002364
2365 DeclGroupRef DG(Function);
2366 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor60406be2010-01-16 22:29:39 +00002368 // This class may have local implicit instantiations that need to be
2369 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002370 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002371 Scope.Exit();
2372
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002373 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002374 // Define any pending vtables.
2375 DefineUsedVTables();
2376
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002377 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002378 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002379 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002381 // Restore the set of pending vtables.
2382 VTableUses.swap(SavedVTableUses);
2383
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002384 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002385 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002386 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002387}
2388
2389/// \brief Instantiate the definition of the given variable from its
2390/// template.
2391///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002392/// \param PointOfInstantiation the point at which the instantiation was
2393/// required. Note that this is not precisely a "point of instantiation"
2394/// for the function, but it's close.
2395///
2396/// \param Var the already-instantiated declaration of a static member
2397/// variable of a class template specialization.
2398///
2399/// \param Recursive if true, recursively instantiates any functions that
2400/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002401///
2402/// \param DefinitionRequired if true, then we are performing an explicit
2403/// instantiation where an out-of-line definition of the member variable
2404/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002405void Sema::InstantiateStaticDataMemberDefinition(
2406 SourceLocation PointOfInstantiation,
2407 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002408 bool Recursive,
2409 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002410 if (Var->isInvalidDecl())
2411 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Douglas Gregor7caa6822009-07-24 20:34:43 +00002413 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002414 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002415 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002416 assert(Def->isStaticDataMember() && "Not a static data member?");
2417 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Douglas Gregor0d035142009-10-27 18:42:08 +00002419 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002420 // We did not find an out-of-line definition of this static data member,
2421 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002422 // instantiate this definition (or provide a specialization for it) in
2423 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002424 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002425 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002426 Diag(PointOfInstantiation,
2427 diag::err_explicit_instantiation_undefined_member)
2428 << 2 << Var->getDeclName() << Var->getDeclContext();
2429 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002430 } else if (Var->getTemplateSpecializationKind()
2431 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002432 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002433 std::make_pair(Var, PointOfInstantiation));
2434 }
2435
Douglas Gregor7caa6822009-07-24 20:34:43 +00002436 return;
2437 }
2438
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002439 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002440 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002441 return;
2442
2443 // C++0x [temp.explicit]p9:
2444 // Except for inline functions, other explicit instantiation declarations
2445 // have the effect of suppressing the implicit instantiation of the entity
2446 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002447 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002448 == TSK_ExplicitInstantiationDeclaration)
2449 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Douglas Gregor7caa6822009-07-24 20:34:43 +00002451 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2452 if (Inst)
2453 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Douglas Gregor7caa6822009-07-24 20:34:43 +00002455 // If we're performing recursive template instantiation, create our own
2456 // queue of pending implicit instantiations that we will instantiate later,
2457 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002458 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002459 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002460 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Douglas Gregor7caa6822009-07-24 20:34:43 +00002462 // Enter the scope of this instantiation. We don't use
2463 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002464 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002466 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002467 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002468 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002469
2470 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002471
2472 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002473 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2474 assert(MSInfo && "Missing member specialization information?");
2475 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2476 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002477 DeclGroupRef DG(Var);
2478 Consumer.HandleTopLevelDecl(DG);
2479 }
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Douglas Gregor7caa6822009-07-24 20:34:43 +00002481 if (Recursive) {
2482 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002483 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002484 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Douglas Gregor7caa6822009-07-24 20:34:43 +00002486 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002487 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002488 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002489}
Douglas Gregor815215d2009-05-27 05:35:12 +00002490
Anders Carlsson09025312009-08-29 05:16:22 +00002491void
2492Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2493 const CXXConstructorDecl *Tmpl,
2494 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Anders Carlsson09025312009-08-29 05:16:22 +00002496 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002497 bool AnyErrors = false;
2498
Anders Carlsson09025312009-08-29 05:16:22 +00002499 // Instantiate all the initializers.
2500 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002501 InitsEnd = Tmpl->init_end();
2502 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002503 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002504
Chandler Carruth030ef472010-09-03 21:54:20 +00002505 // Only instantiate written initializers, let Sema re-construct implicit
2506 // ones.
2507 if (!Init->isWritten())
2508 continue;
2509
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002510 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002511 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002513 SourceLocation EllipsisLoc;
2514
2515 if (Init->isPackExpansion()) {
2516 // This is a pack expansion. We should expand it now.
2517 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2518 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2519 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2520 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002521 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002522 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002523 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2524 BaseTL.getSourceRange(),
2525 Unexpanded.data(),
2526 Unexpanded.size(),
2527 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002528 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002529 NumExpansions)) {
2530 AnyErrors = true;
2531 New->setInvalidDecl();
2532 continue;
2533 }
2534 assert(ShouldExpand && "Partial instantiation of base initializer?");
2535
2536 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002537 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002538 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2539
2540 // Instantiate the initializer.
2541 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2542 LParenLoc, NewArgs, RParenLoc)) {
2543 AnyErrors = true;
2544 break;
2545 }
2546
2547 // Instantiate the base type.
2548 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2549 TemplateArgs,
2550 Init->getSourceLocation(),
2551 New->getDeclName());
2552 if (!BaseTInfo) {
2553 AnyErrors = true;
2554 break;
2555 }
2556
2557 // Build the initializer.
2558 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2559 BaseTInfo,
2560 (Expr **)NewArgs.data(),
2561 NewArgs.size(),
2562 Init->getLParenLoc(),
2563 Init->getRParenLoc(),
2564 New->getParent(),
2565 SourceLocation());
2566 if (NewInit.isInvalid()) {
2567 AnyErrors = true;
2568 break;
2569 }
2570
2571 NewInits.push_back(NewInit.get());
2572 NewArgs.clear();
2573 }
2574
2575 continue;
2576 }
2577
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002578 // Instantiate the initializer.
2579 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002580 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002581 AnyErrors = true;
2582 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002583 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002584
Anders Carlsson09025312009-08-29 05:16:22 +00002585 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002586 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002587 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002588 TemplateArgs,
2589 Init->getSourceLocation(),
2590 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002591 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002592 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002593 New->setInvalidDecl();
2594 continue;
2595 }
2596
John McCalla93c9342009-12-07 02:54:59 +00002597 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002598 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002599 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002600 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002601 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002602 New->getParent(),
2603 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002604 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002605 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002606 Init->getMemberLocation(),
2607 Init->getMember(),
2608 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002609 if (!Member) {
2610 AnyErrors = true;
2611 New->setInvalidDecl();
2612 continue;
2613 }
Mike Stump1eb44332009-09-09 15:08:12 +00002614
2615 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002616 NewArgs.size(),
2617 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002618 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002619 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002620 } else if (Init->isIndirectMemberInitializer()) {
2621 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002622 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002623 Init->getMemberLocation(),
2624 Init->getIndirectMember(), TemplateArgs));
2625
Douglas Gregorb7107222011-03-04 19:46:35 +00002626 if (!IndirectMember) {
2627 AnyErrors = true;
2628 New->setInvalidDecl();
2629 continue;
2630 }
2631
Francois Pichet00eb3f92010-12-04 09:14:42 +00002632 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2633 NewArgs.size(),
2634 Init->getSourceLocation(),
2635 Init->getLParenLoc(),
2636 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002637 }
2638
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002639 if (NewInit.isInvalid()) {
2640 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002641 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002642 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002643 // FIXME: It would be nice if ASTOwningVector had a release function.
2644 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Anders Carlsson09025312009-08-29 05:16:22 +00002646 NewInits.push_back((MemInitTy *)NewInit.get());
2647 }
2648 }
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Anders Carlsson09025312009-08-29 05:16:22 +00002650 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002651 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002652 /*FIXME: ColonLoc */
2653 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002654 NewInits.data(), NewInits.size(),
2655 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002656}
2657
John McCall52a575a2009-08-29 08:11:13 +00002658// TODO: this could be templated if the various decl types used the
2659// same method name.
2660static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2661 ClassTemplateDecl *Instance) {
2662 Pattern = Pattern->getCanonicalDecl();
2663
2664 do {
2665 Instance = Instance->getCanonicalDecl();
2666 if (Pattern == Instance) return true;
2667 Instance = Instance->getInstantiatedFromMemberTemplate();
2668 } while (Instance);
2669
2670 return false;
2671}
2672
Douglas Gregor0d696532009-09-28 06:34:35 +00002673static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2674 FunctionTemplateDecl *Instance) {
2675 Pattern = Pattern->getCanonicalDecl();
2676
2677 do {
2678 Instance = Instance->getCanonicalDecl();
2679 if (Pattern == Instance) return true;
2680 Instance = Instance->getInstantiatedFromMemberTemplate();
2681 } while (Instance);
2682
2683 return false;
2684}
2685
Douglas Gregored9c0f92009-10-29 00:04:11 +00002686static bool
2687isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2688 ClassTemplatePartialSpecializationDecl *Instance) {
2689 Pattern
2690 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2691 do {
2692 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2693 Instance->getCanonicalDecl());
2694 if (Pattern == Instance)
2695 return true;
2696 Instance = Instance->getInstantiatedFromMember();
2697 } while (Instance);
2698
2699 return false;
2700}
2701
John McCall52a575a2009-08-29 08:11:13 +00002702static bool isInstantiationOf(CXXRecordDecl *Pattern,
2703 CXXRecordDecl *Instance) {
2704 Pattern = Pattern->getCanonicalDecl();
2705
2706 do {
2707 Instance = Instance->getCanonicalDecl();
2708 if (Pattern == Instance) return true;
2709 Instance = Instance->getInstantiatedFromMemberClass();
2710 } while (Instance);
2711
2712 return false;
2713}
2714
2715static bool isInstantiationOf(FunctionDecl *Pattern,
2716 FunctionDecl *Instance) {
2717 Pattern = Pattern->getCanonicalDecl();
2718
2719 do {
2720 Instance = Instance->getCanonicalDecl();
2721 if (Pattern == Instance) return true;
2722 Instance = Instance->getInstantiatedFromMemberFunction();
2723 } while (Instance);
2724
2725 return false;
2726}
2727
2728static bool isInstantiationOf(EnumDecl *Pattern,
2729 EnumDecl *Instance) {
2730 Pattern = Pattern->getCanonicalDecl();
2731
2732 do {
2733 Instance = Instance->getCanonicalDecl();
2734 if (Pattern == Instance) return true;
2735 Instance = Instance->getInstantiatedFromMemberEnum();
2736 } while (Instance);
2737
2738 return false;
2739}
2740
John McCalled976492009-12-04 22:46:56 +00002741static bool isInstantiationOf(UsingShadowDecl *Pattern,
2742 UsingShadowDecl *Instance,
2743 ASTContext &C) {
2744 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2745}
2746
2747static bool isInstantiationOf(UsingDecl *Pattern,
2748 UsingDecl *Instance,
2749 ASTContext &C) {
2750 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2751}
2752
John McCall7ba107a2009-11-18 02:36:19 +00002753static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2754 UsingDecl *Instance,
2755 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002756 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002757}
2758
2759static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002760 UsingDecl *Instance,
2761 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002762 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002763}
2764
John McCall52a575a2009-08-29 08:11:13 +00002765static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2766 VarDecl *Instance) {
2767 assert(Instance->isStaticDataMember());
2768
2769 Pattern = Pattern->getCanonicalDecl();
2770
2771 do {
2772 Instance = Instance->getCanonicalDecl();
2773 if (Pattern == Instance) return true;
2774 Instance = Instance->getInstantiatedFromStaticDataMember();
2775 } while (Instance);
2776
2777 return false;
2778}
2779
John McCalled976492009-12-04 22:46:56 +00002780// Other is the prospective instantiation
2781// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002782static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002783 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002784 if (UnresolvedUsingTypenameDecl *UUD
2785 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2786 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2787 return isInstantiationOf(UUD, UD, Ctx);
2788 }
2789 }
2790
2791 if (UnresolvedUsingValueDecl *UUD
2792 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002793 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2794 return isInstantiationOf(UUD, UD, Ctx);
2795 }
2796 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002797
Anders Carlsson0d8df782009-08-29 19:37:28 +00002798 return false;
2799 }
Mike Stump1eb44332009-09-09 15:08:12 +00002800
John McCall52a575a2009-08-29 08:11:13 +00002801 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2802 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002803
John McCall52a575a2009-08-29 08:11:13 +00002804 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2805 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002806
John McCall52a575a2009-08-29 08:11:13 +00002807 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2808 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002809
Douglas Gregor7caa6822009-07-24 20:34:43 +00002810 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002811 if (Var->isStaticDataMember())
2812 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2813
2814 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2815 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002816
Douglas Gregor0d696532009-09-28 06:34:35 +00002817 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2818 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2819
Douglas Gregored9c0f92009-10-29 00:04:11 +00002820 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2821 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2822 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2823 PartialSpec);
2824
Anders Carlssond8b285f2009-09-01 04:26:58 +00002825 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2826 if (!Field->getDeclName()) {
2827 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002828 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002829 cast<FieldDecl>(D);
2830 }
2831 }
Mike Stump1eb44332009-09-09 15:08:12 +00002832
John McCalled976492009-12-04 22:46:56 +00002833 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2834 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2835
2836 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2837 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2838
Douglas Gregor815215d2009-05-27 05:35:12 +00002839 return D->getDeclName() && isa<NamedDecl>(Other) &&
2840 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2841}
2842
2843template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002844static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002845 NamedDecl *D,
2846 ForwardIterator first,
2847 ForwardIterator last) {
2848 for (; first != last; ++first)
2849 if (isInstantiationOf(Ctx, D, *first))
2850 return cast<NamedDecl>(*first);
2851
2852 return 0;
2853}
2854
John McCall02cace72009-08-28 07:59:38 +00002855/// \brief Finds the instantiation of the given declaration context
2856/// within the current instantiation.
2857///
2858/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002859DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002860 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002861 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002862 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002863 return cast_or_null<DeclContext>(ID);
2864 } else return DC;
2865}
2866
Douglas Gregored961e72009-05-27 17:54:46 +00002867/// \brief Find the instantiation of the given declaration within the
2868/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002869///
2870/// This routine is intended to be used when \p D is a declaration
2871/// referenced from within a template, that needs to mapped into the
2872/// corresponding declaration within an instantiation. For example,
2873/// given:
2874///
2875/// \code
2876/// template<typename T>
2877/// struct X {
2878/// enum Kind {
2879/// KnownValue = sizeof(T)
2880/// };
2881///
2882/// bool getKind() const { return KnownValue; }
2883/// };
2884///
2885/// template struct X<int>;
2886/// \endcode
2887///
2888/// In the instantiation of X<int>::getKind(), we need to map the
2889/// EnumConstantDecl for KnownValue (which refers to
2890/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002891/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2892/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002893NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002894 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002895 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002896 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002897 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002898 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002899 // D is a local of some kind. Look into the map of local
2900 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002901 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2902 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2903 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002904
Chris Lattner57ad3782011-02-17 20:34:02 +00002905 if (Found) {
2906 if (Decl *FD = Found->dyn_cast<Decl *>())
2907 return cast<NamedDecl>(FD);
2908
2909 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2910 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2911 }
2912
2913 // If we didn't find the decl, then we must have a label decl that hasn't
2914 // been found yet. Lazily instantiate it and return it now.
2915 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002916
Chris Lattner57ad3782011-02-17 20:34:02 +00002917 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2918 assert(Inst && "Failed to instantiate label??");
2919
2920 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2921 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002922 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002923
Douglas Gregore95b4092009-09-16 18:34:49 +00002924 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2925 if (!Record->isDependentContext())
2926 return D;
2927
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002928 // If the RecordDecl is actually the injected-class-name or a
2929 // "templated" declaration for a class template, class template
2930 // partial specialization, or a member class of a class template,
2931 // substitute into the injected-class-name of the class template
2932 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002933 QualType T;
2934 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2935
2936 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002937 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002938 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2939 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002940 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002941
2942 // If we call SubstType with an InjectedClassNameType here we
2943 // can end up in an infinite loop.
2944 T = Context.getTypeDeclType(Record);
2945 assert(isa<InjectedClassNameType>(T) &&
2946 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002947 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002948 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002949
2950 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002951 // Substitute into the injected-class-name to get the type
2952 // corresponding to the instantiation we want, which may also be
2953 // the current instantiation (if we're in a template
2954 // definition). This substitution should never fail, since we
2955 // know we can instantiate the injected-class-name or we
2956 // wouldn't have gotten to the injected-class-name!
2957
2958 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2959 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00002960 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00002961 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2962
2963 if (!T->isDependentType()) {
2964 assert(T->isRecordType() && "Instantiation must produce a record type");
2965 return T->getAs<RecordType>()->getDecl();
2966 }
2967
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002968 // We are performing "partial" template instantiation to create
2969 // the member declarations for the members of a class template
2970 // specialization. Therefore, D is actually referring to something
2971 // in the current instantiation. Look through the current
2972 // context, which contains actual instantiations, to find the
2973 // instantiation of the "current instantiation" that D refers
2974 // to.
2975 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002976 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002977 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002978 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002979 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002980 if (isInstantiationOf(ClassTemplate,
2981 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002982 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002983
2984 if (!DC->isDependentContext())
2985 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002986 }
2987
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002988 // We're performing "instantiation" of a member of the current
2989 // instantiation while we are type-checking the
2990 // definition. Compute the declaration context and return that.
2991 assert(!SawNonDependentContext &&
2992 "No dependent context while instantiating record");
2993 DeclContext *DC = computeDeclContext(T);
2994 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002995 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002996 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002997 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002998
Douglas Gregore95b4092009-09-16 18:34:49 +00002999 // Fall through to deal with other dependent record types (e.g.,
3000 // anonymous unions in class templates).
3001 }
John McCall52a575a2009-08-29 08:11:13 +00003002
Douglas Gregore95b4092009-09-16 18:34:49 +00003003 if (!ParentDC->isDependentContext())
3004 return D;
3005
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003006 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003007 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003008 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Douglas Gregor815215d2009-05-27 05:35:12 +00003010 if (ParentDC != D->getDeclContext()) {
3011 // We performed some kind of instantiation in the parent context,
3012 // so now we need to look into the instantiated parent context to
3013 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003014
John McCall3cb0ebd2010-03-10 03:28:59 +00003015 // If our context used to be dependent, we may need to instantiate
3016 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003017 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003018 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003019 if (!Spec->isDependentContext()) {
3020 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003021 const RecordType *Tag = T->getAs<RecordType>();
3022 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003023 if (Tag->isBeingDefined())
3024 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003025 if (!Tag->isBeingDefined() &&
3026 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3027 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003028
3029 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003030 }
3031 }
3032
Douglas Gregor815215d2009-05-27 05:35:12 +00003033 NamedDecl *Result = 0;
3034 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003035 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003036 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3037 } else {
3038 // Since we don't have a name for the entity we're looking for,
3039 // our only option is to walk through all of the declarations to
3040 // find that name. This will occur in a few cases:
3041 //
3042 // - anonymous struct/union within a template
3043 // - unnamed class/struct/union/enum within a template
3044 //
3045 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003046 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003047 ParentDC->decls_begin(),
3048 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003049 }
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003051 if (!Result) {
3052 if (isa<UsingShadowDecl>(D)) {
3053 // UsingShadowDecls can instantiate to nothing because of using hiding.
3054 } else if (Diags.hasErrorOccurred()) {
3055 // We've already complained about something, so most likely this
3056 // declaration failed to instantiate. There's no point in complaining
3057 // further, since this is normal in invalid code.
3058 } else if (IsBeingInstantiated) {
3059 // The class in which this member exists is currently being
3060 // instantiated, and we haven't gotten around to instantiating this
3061 // member yet. This can happen when the code uses forward declarations
3062 // of member classes, and introduces ordering dependencies via
3063 // template instantiation.
3064 Diag(Loc, diag::err_member_not_yet_instantiated)
3065 << D->getDeclName()
3066 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3067 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3068 } else {
3069 // We should have found something, but didn't.
3070 llvm_unreachable("Unable to find instantiation of declaration!");
3071 }
3072 }
3073
Douglas Gregor815215d2009-05-27 05:35:12 +00003074 D = Result;
3075 }
3076
Douglas Gregor815215d2009-05-27 05:35:12 +00003077 return D;
3078}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003079
Mike Stump1eb44332009-09-09 15:08:12 +00003080/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003081/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003082void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003083 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003084 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003085 PendingImplicitInstantiation Inst;
3086
3087 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003088 Inst = PendingInstantiations.front();
3089 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003090 } else {
3091 Inst = PendingLocalImplicitInstantiations.front();
3092 PendingLocalImplicitInstantiations.pop_front();
3093 }
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Douglas Gregor7caa6822009-07-24 20:34:43 +00003095 // Instantiate function definitions
3096 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003097 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3098 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003099 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3100 TSK_ExplicitInstantiationDefinition;
3101 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3102 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003103 continue;
3104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Douglas Gregor7caa6822009-07-24 20:34:43 +00003106 // Instantiate static data member definitions.
3107 VarDecl *Var = cast<VarDecl>(Inst.first);
3108 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003109
Chandler Carruth291b4412010-02-13 10:17:50 +00003110 // Don't try to instantiate declarations if the most recent redeclaration
3111 // is invalid.
3112 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3113 continue;
3114
3115 // Check if the most recent declaration has changed the specialization kind
3116 // and removed the need for implicit instantiation.
3117 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3118 case TSK_Undeclared:
3119 assert(false && "Cannot instantitiate an undeclared specialization.");
3120 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003121 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003122 continue; // No longer need to instantiate this type.
3123 case TSK_ExplicitInstantiationDefinition:
3124 // We only need an instantiation if the pending instantiation *is* the
3125 // explicit instantiation.
3126 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003127 case TSK_ImplicitInstantiation:
3128 break;
3129 }
3130
John McCallf312b1e2010-08-26 23:41:50 +00003131 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3132 "instantiating static data member "
3133 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Chandler Carruth58e390e2010-08-25 08:27:02 +00003135 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3136 TSK_ExplicitInstantiationDefinition;
3137 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3138 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003139 }
3140}
John McCall0c01d182010-03-24 05:22:00 +00003141
3142void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3143 const MultiLevelTemplateArgumentList &TemplateArgs) {
3144 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3145 E = Pattern->ddiag_end(); I != E; ++I) {
3146 DependentDiagnostic *DD = *I;
3147
3148 switch (DD->getKind()) {
3149 case DependentDiagnostic::Access:
3150 HandleDependentAccessCheck(*DD, TemplateArgs);
3151 break;
3152 }
3153 }
3154}