blob: b668e173867639e087337f57f47169b6fd049105 [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
148 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000149 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,
267 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000268 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000269 D->getStorageClass(),
270 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000271 Var->setThreadSpecified(D->isThreadSpecified());
272 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000273
John McCallb6217662010-03-15 10:12:16 +0000274 // Substitute the nested name specifier, if any.
275 if (SubstQualifier(D, Var))
276 return 0;
277
Mike Stump1eb44332009-09-09 15:08:12 +0000278 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000279 // out-of-line, the instantiation will have the same lexical
280 // context (which will be a namespace scope) as the template.
281 if (D->isOutOfLine())
282 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCall46460a62010-01-20 21:53:11 +0000284 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000285
286 if (!D->isStaticDataMember())
287 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000288
Mike Stump390b4cc2009-05-16 07:39:55 +0000289 // FIXME: In theory, we could have a previous declaration for variables that
290 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000291 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000292 // FIXME: having to fake up a LookupResult is dumb.
293 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000294 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000295 if (D->isStaticDataMember())
296 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000297 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Douglas Gregor7caa6822009-07-24 20:34:43 +0000299 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000300 if (!D->isStaticDataMember())
301 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000302 Owner->makeDeclVisibleInContext(Var);
303 } else {
304 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000305 if (Owner->isFunctionOrMethod())
306 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000307 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000308 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000309
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000310 // Link instantiations of static data members back to the template from
311 // which they were instantiated.
312 if (Var->isStaticDataMember())
313 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000314 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000315
Douglas Gregor60c93c92010-02-09 07:26:29 +0000316 if (Var->getAnyInitializer()) {
317 // We already have an initializer in the class.
318 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000319 if (Var->isStaticDataMember() && !D->isOutOfLine())
320 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
321 else
322 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
323
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000324 // Instantiate the initializer.
325 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000326 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000327 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000328 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000329 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000330 // Attach the initializer to the declaration, if we have one.
331 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000332 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000333 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000334 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000335 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000336 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000337 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000338 RParenLoc,
339 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000340 } else {
341 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000342 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000343 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000344 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000345 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000346 // FIXME: Not too happy about invalidating the declaration
347 // because of a bogus initializer.
348 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000349 }
350
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000351 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000352 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000353 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000354
Douglas Gregor5764f612010-05-08 23:05:03 +0000355 // Diagnose unused local variables.
356 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
357 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000358
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000359 return Var;
360}
361
Abramo Bagnara6206d532010-06-05 05:09:32 +0000362Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
363 AccessSpecDecl* AD
364 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
365 D->getAccessSpecifierLoc(), D->getColonLoc());
366 Owner->addHiddenDecl(AD);
367 return AD;
368}
369
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
371 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000372 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000373 if (DI->getType()->isDependentType() ||
374 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000375 DI = SemaRef.SubstType(DI, TemplateArgs,
376 D->getLocation(), D->getDeclName());
377 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000378 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000379 Invalid = true;
380 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000381 // C++ [temp.arg.type]p3:
382 // If a declaration acquires a function type through a type
383 // dependent on a template-parameter and this causes a
384 // declaration that does not use the syntactic form of a
385 // function declarator to have function type, the program is
386 // ill-formed.
387 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000388 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000389 Invalid = true;
390 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000391 } else {
392 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393 }
394
395 Expr *BitWidth = D->getBitWidth();
396 if (Invalid)
397 BitWidth = 0;
398 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000399 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000400 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000401
John McCall60d7b3a2010-08-24 06:29:42 +0000402 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000403 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000404 if (InstantiatedBitWidth.isInvalid()) {
405 Invalid = true;
406 BitWidth = 0;
407 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000408 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409 }
410
John McCall07fb6be2009-10-22 23:33:21 +0000411 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
412 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000413 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000414 D->getLocation(),
415 D->isMutable(),
416 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000417 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000418 D->getAccess(),
419 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000420 if (!Field) {
421 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000422 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
John McCall1d8d1cc2010-08-01 02:01:53 +0000425 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000426
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000427 if (Invalid)
428 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000430 if (!Field->getDeclName()) {
431 // Keep track of where this decl came from.
432 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000433 }
434 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
435 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000436 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000437 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000440 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000441 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000443
444 return Field;
445}
446
Francois Pichet87c2e122010-11-21 06:08:52 +0000447Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
448 NamedDecl **NamedChain =
449 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
450
451 int i = 0;
452 for (IndirectFieldDecl::chain_iterator PI =
453 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000454 PI != PE; ++PI) {
455 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
456 TemplateArgs);
457 if (!Next)
458 return 0;
459
460 NamedChain[i++] = Next;
461 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000462
Francois Pichet40e17752010-12-09 10:07:54 +0000463 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000464 IndirectFieldDecl* IndirectField
465 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000466 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000467 NamedChain, D->getChainingSize());
468
469
470 IndirectField->setImplicit(D->isImplicit());
471 IndirectField->setAccess(D->getAccess());
472 Owner->addDecl(IndirectField);
473 return IndirectField;
474}
475
John McCall02cace72009-08-28 07:59:38 +0000476Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000477 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000478 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000479 if (TypeSourceInfo *Ty = D->getFriendType()) {
480 TypeSourceInfo *InstTy =
481 SemaRef.SubstType(Ty, TemplateArgs,
482 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000483 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000484 return 0;
John McCall02cace72009-08-28 07:59:38 +0000485
Douglas Gregor06245bf2010-04-07 17:57:12 +0000486 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
487 if (!FD)
488 return 0;
489
490 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000491 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000492 Owner->addDecl(FD);
493 return FD;
494 }
495
496 NamedDecl *ND = D->getFriendDecl();
497 assert(ND && "friend decl must be a decl or a type!");
498
John McCallaf2094e2010-04-08 09:05:18 +0000499 // All of the Visit implementations for the various potential friend
500 // declarations have to be carefully written to work for friend
501 // objects, with the most important detail being that the target
502 // decl should almost certainly not be placed in Owner.
503 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000504 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
John McCall02cace72009-08-28 07:59:38 +0000506 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000507 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
508 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000509 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000510 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000511 Owner->addDecl(FD);
512 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000513}
514
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000515Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
516 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregorac7610d2009-06-22 20:57:11 +0000518 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000519 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000520
John McCall60d7b3a2010-08-24 06:29:42 +0000521 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000522 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000523 if (InstantiatedAssertExpr.isInvalid())
524 return 0;
525
John McCall60d7b3a2010-08-24 06:29:42 +0000526 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000527 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000528 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000529 InstantiatedAssertExpr.get(),
530 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000531}
532
533Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000534 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000536 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000537 /*PrevDecl=*/0, D->isScoped(),
538 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000539 if (D->isFixed()) {
540 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
541 // If we have type source information for the underlying type, it means it
542 // has been explicitly set by the user. Perform substitution on it before
543 // moving on.
544 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
545 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
546 TemplateArgs,
547 UnderlyingLoc,
548 DeclarationName()));
549
550 if (!Enum->getIntegerTypeSourceInfo())
551 Enum->setIntegerType(SemaRef.Context.IntTy);
552 }
553 else {
554 assert(!D->getIntegerType()->isDependentType()
555 && "Dependent type without type source info");
556 Enum->setIntegerType(D->getIntegerType());
557 }
558 }
559
John McCall5b629aa2010-10-22 23:36:17 +0000560 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
561
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000562 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000563 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000564 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000565 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000566 Enum->startDefinition();
567
Douglas Gregor96084f12010-03-01 19:00:07 +0000568 if (D->getDeclContext()->isFunctionOrMethod())
569 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
570
John McCalld226f652010-08-21 09:40:31 +0000571 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000572
573 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000574 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
575 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000576 EC != ECEnd; ++EC) {
577 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000578 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000579 if (Expr *UninstValue = EC->getInitExpr()) {
580 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000581 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000582 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000583
John McCallce3ff2b2009-08-25 22:02:44 +0000584 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000585 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586
587 // Drop the initial value and continue.
588 bool isInvalid = false;
589 if (Value.isInvalid()) {
590 Value = SemaRef.Owned((Expr *)0);
591 isInvalid = true;
592 }
593
Mike Stump1eb44332009-09-09 15:08:12 +0000594 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000595 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
596 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000597 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000598
599 if (isInvalid) {
600 if (EnumConst)
601 EnumConst->setInvalidDecl();
602 Enum->setInvalidDecl();
603 }
604
605 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000606 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
607
John McCall3b85ecf2010-01-23 22:37:59 +0000608 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000609 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000610 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000611 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000612
613 if (D->getDeclContext()->isFunctionOrMethod()) {
614 // If the enumeration is within a function or method, record the enum
615 // constant as a local.
616 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
617 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000618 }
619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000621 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000622 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000623 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000624 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000625 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000626 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000627
628 return Enum;
629}
630
Douglas Gregor6477b692009-03-25 15:04:13 +0000631Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
632 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
633 return 0;
634}
635
John McCalle29ba202009-08-20 01:44:21 +0000636Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000637 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
638
Douglas Gregor550d9b22009-10-31 17:21:17 +0000639 // Create a local instantiation scope for this class template, which
640 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000641 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000642 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000643 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000644 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000645 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000646
647 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000648
649 // Instantiate the qualifier. We have to do this first in case
650 // we're a friend declaration, because if we are then we need to put
651 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000652 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
653 if (QualifierLoc) {
654 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
655 TemplateArgs);
656 if (!QualifierLoc)
657 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000658 }
659
660 CXXRecordDecl *PrevDecl = 0;
661 ClassTemplateDecl *PrevClassTemplate = 0;
662
Nick Lewycky37574f52010-11-08 23:29:42 +0000663 if (!isFriend && Pattern->getPreviousDeclaration()) {
664 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
665 if (Found.first != Found.second) {
666 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
667 if (PrevClassTemplate)
668 PrevDecl = PrevClassTemplate->getTemplatedDecl();
669 }
670 }
671
John McCall93ba8572010-03-25 06:39:04 +0000672 // If this isn't a friend, then it's a member template, in which
673 // case we just want to build the instantiation in the
674 // specialization. If it is a friend, we want to build it in
675 // the appropriate context.
676 DeclContext *DC = Owner;
677 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000678 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000679 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000680 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000681 DC = SemaRef.computeDeclContext(SS);
682 if (!DC) return 0;
683 } else {
684 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
685 Pattern->getDeclContext(),
686 TemplateArgs);
687 }
688
689 // Look for a previous declaration of the template in the owning
690 // context.
691 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
692 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
693 SemaRef.LookupQualifiedName(R, DC);
694
695 if (R.isSingleResult()) {
696 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
697 if (PrevClassTemplate)
698 PrevDecl = PrevClassTemplate->getTemplatedDecl();
699 }
700
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000701 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000702 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000703 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000704 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000705 return 0;
706 }
707
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000708 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000709 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000710 bool Complain = true;
711
712 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
713 // template for struct std::tr1::__detail::_Map_base, where the
714 // template parameters of the friend declaration don't match the
715 // template parameters of the original declaration. In this one
716 // case, we don't complain about the ill-formed friend
717 // declaration.
718 if (isFriend && Pattern->getIdentifier() &&
719 Pattern->getIdentifier()->isStr("_Map_base") &&
720 DC->isNamespace() &&
721 cast<NamespaceDecl>(DC)->getIdentifier() &&
722 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
723 DeclContext *DCParent = DC->getParent();
724 if (DCParent->isNamespace() &&
725 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
726 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
727 DeclContext *DCParent2 = DCParent->getParent();
728 if (DCParent2->isNamespace() &&
729 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
730 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
731 DCParent2->getParent()->isTranslationUnit())
732 Complain = false;
733 }
734 }
735
John McCall93ba8572010-03-25 06:39:04 +0000736 TemplateParameterList *PrevParams
737 = PrevClassTemplate->getTemplateParameters();
738
739 // Make sure the parameter lists match.
740 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000741 Complain,
742 Sema::TPL_TemplateMatch)) {
743 if (Complain)
744 return 0;
745
746 AdoptedPreviousTemplateParams = true;
747 InstParams = PrevParams;
748 }
John McCall93ba8572010-03-25 06:39:04 +0000749
750 // Do some additional validation, then merge default arguments
751 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000752 if (!AdoptedPreviousTemplateParams &&
753 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000754 Sema::TPC_ClassTemplate))
755 return 0;
756 }
757 }
758
John McCalle29ba202009-08-20 01:44:21 +0000759 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000760 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000761 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000762 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000763 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000764
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000765 if (QualifierLoc)
766 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000767
John McCalle29ba202009-08-20 01:44:21 +0000768 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000769 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
770 D->getIdentifier(), InstParams, RecordInst,
771 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000772 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000773
John McCall93ba8572010-03-25 06:39:04 +0000774 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000775 if (PrevClassTemplate)
776 Inst->setAccess(PrevClassTemplate->getAccess());
777 else
778 Inst->setAccess(D->getAccess());
779
John McCall93ba8572010-03-25 06:39:04 +0000780 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
781 // TODO: do we want to track the instantiation progeny of this
782 // friend target decl?
783 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000784 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000785 if (!PrevClassTemplate)
786 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000787 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000788
789 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000790 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000791 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000792
Douglas Gregor259571e2009-10-30 22:42:42 +0000793 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000794 if (isFriend) {
795 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000796 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000797 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000798
John McCalle29ba202009-08-20 01:44:21 +0000799 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000800
801 if (!PrevClassTemplate) {
802 // Queue up any out-of-line partial specializations of this member
803 // class template; the client will force their instantiation once
804 // the enclosing class has been instantiated.
805 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
806 D->getPartialSpecializations(PartialSpecs);
807 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
808 if (PartialSpecs[I]->isOutOfLine())
809 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
810 }
811
John McCalle29ba202009-08-20 01:44:21 +0000812 return Inst;
813}
814
Douglas Gregord60e1052009-08-27 16:57:43 +0000815Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000816TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
817 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000818 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
819
820 // Lookup the already-instantiated declaration in the instantiation
821 // of the class template and return that.
822 DeclContext::lookup_result Found
823 = Owner->lookup(ClassTemplate->getDeclName());
824 if (Found.first == Found.second)
825 return 0;
826
827 ClassTemplateDecl *InstClassTemplate
828 = dyn_cast<ClassTemplateDecl>(*Found.first);
829 if (!InstClassTemplate)
830 return 0;
831
Douglas Gregord65587f2010-11-10 19:44:59 +0000832 if (ClassTemplatePartialSpecializationDecl *Result
833 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
834 return Result;
835
836 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000837}
838
839Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000840TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000841 // Create a local instantiation scope for this function template, which
842 // will contain the instantiations of the template parameters and then get
843 // merged with the local instantiation scope for the function template
844 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000845 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000846
Douglas Gregord60e1052009-08-27 16:57:43 +0000847 TemplateParameterList *TempParams = D->getTemplateParameters();
848 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000849 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000851
Douglas Gregora735b202009-10-13 14:39:41 +0000852 FunctionDecl *Instantiated = 0;
853 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
854 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
855 InstParams));
856 else
857 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
858 D->getTemplatedDecl(),
859 InstParams));
860
861 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000862 return 0;
863
John McCall46460a62010-01-20 21:53:11 +0000864 Instantiated->setAccess(D->getAccess());
865
Mike Stump1eb44332009-09-09 15:08:12 +0000866 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000867 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000868 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000869 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000870 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000871 assert(InstTemplate &&
872 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000873
John McCallb1a56e72010-03-26 23:10:15 +0000874 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
875
John McCalle976ffe2009-12-14 23:19:40 +0000876 // Link the instantiation back to the pattern *unless* this is a
877 // non-definition friend declaration.
878 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000879 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000880 InstTemplate->setInstantiatedFromMemberTemplate(D);
881
John McCallb1a56e72010-03-26 23:10:15 +0000882 // Make declarations visible in the appropriate context.
883 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000884 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000885
Douglas Gregord60e1052009-08-27 16:57:43 +0000886 return InstTemplate;
887}
888
Douglas Gregord475b8d2009-03-25 21:17:03 +0000889Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
890 CXXRecordDecl *PrevDecl = 0;
891 if (D->isInjectedClassName())
892 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000893 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000894 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
895 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000896 TemplateArgs);
897 if (!Prev) return 0;
898 PrevDecl = cast<CXXRecordDecl>(Prev);
899 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000900
901 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000902 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000903 D->getLocation(), D->getIdentifier(),
904 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000905
906 // Substitute the nested name specifier, if any.
907 if (SubstQualifier(D, Record))
908 return 0;
909
Douglas Gregord475b8d2009-03-25 21:17:03 +0000910 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000911 // FIXME: Check against AS_none is an ugly hack to work around the issue that
912 // the tag decls introduced by friend class declarations don't have an access
913 // specifier. Remove once this area of the code gets sorted out.
914 if (D->getAccess() != AS_none)
915 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000916 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000917 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000918
John McCall02cace72009-08-28 07:59:38 +0000919 // If the original function was part of a friend declaration,
920 // inherit its namespace state.
921 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
922 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
923
Douglas Gregor9901c572010-05-21 00:31:19 +0000924 // Make sure that anonymous structs and unions are recorded.
925 if (D->isAnonymousStructOrUnion()) {
926 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000927 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000928 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
929 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000930
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000931 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000932 return Record;
933}
934
John McCall02cace72009-08-28 07:59:38 +0000935/// Normal class members are of more specific types and therefore
936/// don't make it here. This function serves two purposes:
937/// 1) instantiating function templates
938/// 2) substituting friend declarations
939/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000940Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000941 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000942 // Check whether there is already a function template specialization for
943 // this declaration.
944 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
945 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000946 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000947 std::pair<const TemplateArgument *, unsigned> Innermost
948 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000950 FunctionDecl *SpecFunc
951 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
952 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Douglas Gregor127102b2009-06-29 20:59:39 +0000954 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000955 if (SpecFunc)
956 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000957 }
Mike Stump1eb44332009-09-09 15:08:12 +0000958
John McCallb0cb0222010-03-27 05:57:59 +0000959 bool isFriend;
960 if (FunctionTemplate)
961 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
962 else
963 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
964
Douglas Gregor79c22782010-01-16 20:21:20 +0000965 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000966 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000967 !(isa<Decl>(Owner) &&
968 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000969 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregore53060f2009-06-25 22:08:12 +0000971 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000972 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
973 TInfo = SubstFunctionType(D, Params);
974 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000975 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000976 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000977
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000978 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
979 if (QualifierLoc) {
980 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
981 TemplateArgs);
982 if (!QualifierLoc)
983 return 0;
John McCalld325daa2010-03-26 04:53:08 +0000984 }
985
John McCall68b6b872010-02-06 01:50:47 +0000986 // If we're instantiating a local function declaration, put the result
987 // in the owner; otherwise we need to find the instantiated context.
988 DeclContext *DC;
989 if (D->getDeclContext()->isFunctionOrMethod())
990 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000991 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +0000992 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000993 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +0000994 DC = SemaRef.computeDeclContext(SS);
995 if (!DC) return 0;
996 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000997 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
998 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000999 }
John McCall68b6b872010-02-06 01:50:47 +00001000
John McCall02cace72009-08-28 07:59:38 +00001001 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001002 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001003 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001004 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001005 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001006
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001007 if (QualifierLoc)
1008 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001009
John McCallb1a56e72010-03-26 23:10:15 +00001010 DeclContext *LexicalDC = Owner;
1011 if (!isFriend && D->isOutOfLine()) {
1012 assert(D->getDeclContext()->isFileContext());
1013 LexicalDC = D->getDeclContext();
1014 }
1015
1016 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Douglas Gregore53060f2009-06-25 22:08:12 +00001018 // Attach the parameters
1019 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001020 if (Params[P])
1021 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001022 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001023
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001024 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001025 if (TemplateParams) {
1026 // Our resulting instantiation is actually a function template, since we
1027 // are substituting only the outer template parameters. For example, given
1028 //
1029 // template<typename T>
1030 // struct X {
1031 // template<typename U> friend void f(T, U);
1032 // };
1033 //
1034 // X<int> x;
1035 //
1036 // We are instantiating the friend function template "f" within X<int>,
1037 // which means substituting int for T, but leaving "f" as a friend function
1038 // template.
1039 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001040 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001041 Function->getLocation(),
1042 Function->getDeclName(),
1043 TemplateParams, Function);
1044 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001045
1046 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001047
1048 if (isFriend && D->isThisDeclarationADefinition()) {
1049 // TODO: should we remember this connection regardless of whether
1050 // the friend declaration provided a body?
1051 FunctionTemplate->setInstantiatedFromMemberTemplate(
1052 D->getDescribedFunctionTemplate());
1053 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001054 } else if (FunctionTemplate) {
1055 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001056 std::pair<const TemplateArgument *, unsigned> Innermost
1057 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001058 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001059 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001060 Innermost.first,
1061 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001062 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001063 } else if (isFriend && D->isThisDeclarationADefinition()) {
1064 // TODO: should we remember this connection regardless of whether
1065 // the friend declaration provided a body?
1066 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001067 }
Douglas Gregora735b202009-10-13 14:39:41 +00001068
Douglas Gregore53060f2009-06-25 22:08:12 +00001069 if (InitFunctionInstantiation(Function, D))
1070 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregore53060f2009-06-25 22:08:12 +00001072 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001073 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001074
John McCall68263142009-11-18 22:49:29 +00001075 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1076 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1077
John McCallaf2094e2010-04-08 09:05:18 +00001078 if (DependentFunctionTemplateSpecializationInfo *Info
1079 = D->getDependentSpecializationInfo()) {
1080 assert(isFriend && "non-friend has dependent specialization info?");
1081
1082 // This needs to be set now for future sanity.
1083 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1084
1085 // Instantiate the explicit template arguments.
1086 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1087 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001088 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1089 ExplicitArgs, TemplateArgs))
1090 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001091
1092 // Map the candidate templates to their instantiations.
1093 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1094 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1095 Info->getTemplate(I),
1096 TemplateArgs);
1097 if (!Temp) return 0;
1098
1099 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1100 }
1101
1102 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1103 &ExplicitArgs,
1104 Previous))
1105 Function->setInvalidDecl();
1106
1107 isExplicitSpecialization = true;
1108
1109 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // Look only into the namespace where the friend would be declared to
1111 // find a previous declaration. This is the innermost enclosing namespace,
1112 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001113 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001114
Douglas Gregora735b202009-10-13 14:39:41 +00001115 // In C++, the previous declaration we find might be a tag type
1116 // (class or enum). In this case, the new declaration will hide the
1117 // tag type. Note that this does does not apply if we're declaring a
1118 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001119 if (Previous.isSingleTagDecl())
1120 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001121 }
1122
John McCall9f54ad42009-12-10 09:41:52 +00001123 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001124 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001125
John McCall76d32642010-04-24 01:30:58 +00001126 NamedDecl *PrincipalDecl = (TemplateParams
1127 ? cast<NamedDecl>(FunctionTemplate)
1128 : Function);
1129
Douglas Gregora735b202009-10-13 14:39:41 +00001130 // If the original function was part of a friend declaration,
1131 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001132 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001133 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001134 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001135 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001136 else
Douglas Gregora735b202009-10-13 14:39:41 +00001137 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001138
1139 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1140 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001141
Gabor Greif77535df2010-08-30 22:25:56 +00001142 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001143
Douglas Gregor238058c2010-05-18 05:45:02 +00001144 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1145 D->isThisDeclarationADefinition()) {
1146 // Check for a function body.
1147 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001148 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001149 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1150 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1151 << Function->getDeclName();
1152 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1153 Function->setInvalidDecl();
1154 }
1155 // Check for redefinitions due to other instantiations of this or
1156 // a similar friend function.
1157 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1158 REnd = Function->redecls_end();
1159 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001160 if (*R == Function)
1161 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001162 switch (R->getFriendObjectKind()) {
1163 case Decl::FOK_None:
1164 if (!queuedInstantiation && R->isUsed(false)) {
1165 if (MemberSpecializationInfo *MSInfo
1166 = Function->getMemberSpecializationInfo()) {
1167 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1168 SourceLocation Loc = R->getLocation(); // FIXME
1169 MSInfo->setPointOfInstantiation(Loc);
1170 SemaRef.PendingLocalImplicitInstantiations.push_back(
1171 std::make_pair(Function, Loc));
1172 queuedInstantiation = true;
1173 }
1174 }
1175 }
1176 break;
1177 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001178 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001179 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001180 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001181 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1182 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001183 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001184 Function->setInvalidDecl();
1185 break;
1186 }
1187 }
1188 }
1189 }
Douglas Gregora735b202009-10-13 14:39:41 +00001190 }
1191
John McCall76d32642010-04-24 01:30:58 +00001192 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1193 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1194 PrincipalDecl->setNonMemberOperator();
1195
Douglas Gregore53060f2009-06-25 22:08:12 +00001196 return Function;
1197}
1198
Douglas Gregord60e1052009-08-27 16:57:43 +00001199Decl *
1200TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1201 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001202 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1203 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001204 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001205 // We are creating a function template specialization from a function
1206 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001207 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001208 std::pair<const TemplateArgument *, unsigned> Innermost
1209 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001211 FunctionDecl *SpecFunc
1212 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1213 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Douglas Gregor6b906862009-08-21 00:16:32 +00001215 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001216 if (SpecFunc)
1217 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001218 }
1219
John McCallb0cb0222010-03-27 05:57:59 +00001220 bool isFriend;
1221 if (FunctionTemplate)
1222 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1223 else
1224 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1225
Douglas Gregor79c22782010-01-16 20:21:20 +00001226 bool MergeWithParentScope = (TemplateParams != 0) ||
1227 !(isa<Decl>(Owner) &&
1228 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001229 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001230
John McCall4eab39f2010-10-19 02:26:41 +00001231 // Instantiate enclosing template arguments for friends.
1232 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1233 unsigned NumTempParamLists = 0;
1234 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1235 TempParamLists.set_size(NumTempParamLists);
1236 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1237 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1238 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1239 if (!InstParams)
1240 return NULL;
1241 TempParamLists[I] = InstParams;
1242 }
1243 }
1244
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001245 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001246 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1247 TInfo = SubstFunctionType(D, Params);
1248 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001249 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001250 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001251
Abramo Bagnara723df242010-12-14 22:11:44 +00001252 // \brief If the type of this function, after ignoring parentheses,
1253 // is not *directly* a function type, then we're instantiating a function
1254 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001255 //
1256 // typedef int functype(int, int);
1257 // functype func;
1258 //
1259 // In this case, we'll just go instantiate the ParmVarDecls that we
1260 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001261 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001262 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001263 llvm::SmallVector<QualType, 4> ParamTypes;
1264 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1265 D->getNumParams(), TemplateArgs, ParamTypes,
1266 &Params))
1267 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001268 }
1269
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001270 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1271 if (QualifierLoc) {
1272 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001273 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001274 if (!QualifierLoc)
1275 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001276 }
1277
1278 DeclContext *DC = Owner;
1279 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001280 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001281 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001282 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001283 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001284
1285 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1286 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001287 } else {
1288 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1289 D->getDeclContext(),
1290 TemplateArgs);
1291 }
1292 if (!DC) return 0;
1293 }
1294
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001295 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001296 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001297 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Abramo Bagnara25777432010-08-11 22:01:17 +00001299 DeclarationNameInfo NameInfo
1300 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001301 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001302 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001303 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001304 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001305 Constructor->isInlineSpecified(),
1306 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001307 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001308 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001309 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001310 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001311 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001312 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001313 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001314 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001315 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001316 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001317 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001318 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1319 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001320 D->isStatic(),
1321 D->getStorageClassAsWritten(),
1322 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001323 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001324
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001325 if (QualifierLoc)
1326 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001327
Douglas Gregord60e1052009-08-27 16:57:43 +00001328 if (TemplateParams) {
1329 // Our resulting instantiation is actually a function template, since we
1330 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001331 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001332 // template<typename T>
1333 // struct X {
1334 // template<typename U> void f(T, U);
1335 // };
1336 //
1337 // X<int> x;
1338 //
1339 // We are instantiating the member template "f" within X<int>, which means
1340 // substituting int for T, but leaving "f" as a member function template.
1341 // Build the function template itself.
1342 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1343 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001344 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001345 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001346 if (isFriend) {
1347 FunctionTemplate->setLexicalDeclContext(Owner);
1348 FunctionTemplate->setObjectOfFriendDecl(true);
1349 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001350 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001351 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001352 } else if (FunctionTemplate) {
1353 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001354 std::pair<const TemplateArgument *, unsigned> Innermost
1355 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001356 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001357 TemplateArgumentList::CreateCopy(SemaRef.Context,
1358 Innermost.first,
1359 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001360 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001361 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001362 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001363 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001364 }
1365
Mike Stump1eb44332009-09-09 15:08:12 +00001366 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001367 // out-of-line, the instantiation will have the same lexical
1368 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001369 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001370 if (NumTempParamLists)
1371 Method->setTemplateParameterListsInfo(SemaRef.Context,
1372 NumTempParamLists,
1373 TempParamLists.data());
1374
John McCallb0cb0222010-03-27 05:57:59 +00001375 Method->setLexicalDeclContext(Owner);
1376 Method->setObjectOfFriendDecl(true);
1377 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001378 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregor5545e162009-03-24 00:38:23 +00001380 // Attach the parameters
1381 for (unsigned P = 0; P < Params.size(); ++P)
1382 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001383 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001384
1385 if (InitMethodInstantiation(Method, D))
1386 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001387
Abramo Bagnara25777432010-08-11 22:01:17 +00001388 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1389 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001390
John McCallb0cb0222010-03-27 05:57:59 +00001391 if (!FunctionTemplate || TemplateParams || isFriend) {
1392 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregordec06662009-08-21 18:42:58 +00001394 // In C++, the previous declaration we find might be a tag type
1395 // (class or enum). In this case, the new declaration will hide the
1396 // tag type. Note that this does does not apply if we're declaring a
1397 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001398 if (Previous.isSingleTagDecl())
1399 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001400 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001401
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001402 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001403 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001404
Douglas Gregor4ba31362009-12-01 17:24:26 +00001405 if (D->isPure())
1406 SemaRef.CheckPureMethod(Method, SourceRange());
1407
John McCall46460a62010-01-20 21:53:11 +00001408 Method->setAccess(D->getAccess());
1409
Anders Carlsson9eefa222011-01-20 06:52:44 +00001410 SemaRef.CheckOverrideControl(Method);
1411
John McCallb0cb0222010-03-27 05:57:59 +00001412 if (FunctionTemplate) {
1413 // If there's a function template, let our caller handle it.
1414 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1415 // Don't hide a (potentially) valid declaration with an invalid one.
1416 } else {
1417 NamedDecl *DeclToAdd = (TemplateParams
1418 ? cast<NamedDecl>(FunctionTemplate)
1419 : Method);
1420 if (isFriend)
1421 Record->makeDeclVisibleInContext(DeclToAdd);
1422 else
1423 Owner->addDecl(DeclToAdd);
1424 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001425
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001426 return Method;
1427}
1428
Douglas Gregor615c5d42009-03-24 16:43:20 +00001429Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001430 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001431}
1432
Douglas Gregor03b2b072009-03-24 00:15:49 +00001433Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001434 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001435}
1436
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001437Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001438 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001439}
1440
Douglas Gregor6477b692009-03-25 15:04:13 +00001441ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001442 return SemaRef.SubstParmVarDecl(D, TemplateArgs, llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001443}
1444
John McCalle29ba202009-08-20 01:44:21 +00001445Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1446 TemplateTypeParmDecl *D) {
1447 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001448 const Type* T = D->getTypeForDecl();
1449 assert(T->isTemplateTypeParmType());
1450 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001451
John McCalle29ba202009-08-20 01:44:21 +00001452 TemplateTypeParmDecl *Inst =
1453 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001454 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001455 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001456 D->wasDeclaredWithTypename(),
1457 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001458 Inst->setAccess(AS_public);
1459
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001460 if (D->hasDefaultArgument())
1461 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001462
Douglas Gregor550d9b22009-10-31 17:21:17 +00001463 // Introduce this template parameter's instantiation into the instantiation
1464 // scope.
1465 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1466
John McCalle29ba202009-08-20 01:44:21 +00001467 return Inst;
1468}
1469
Douglas Gregor33642df2009-10-23 23:25:44 +00001470Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1471 NonTypeTemplateParmDecl *D) {
1472 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001473 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1474 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1475 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1476 bool IsExpandedParameterPack = false;
1477 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001478 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001479 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001480
1481 if (D->isExpandedParameterPack()) {
1482 // The non-type template parameter pack is an already-expanded pack
1483 // expansion of types. Substitute into each of the expanded types.
1484 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1485 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1486 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1487 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1488 TemplateArgs,
1489 D->getLocation(),
1490 D->getDeclName());
1491 if (!NewDI)
1492 return 0;
1493
1494 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1495 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1496 D->getLocation());
1497 if (NewT.isNull())
1498 return 0;
1499 ExpandedParameterPackTypes.push_back(NewT);
1500 }
1501
1502 IsExpandedParameterPack = true;
1503 DI = D->getTypeSourceInfo();
1504 T = DI->getType();
1505 } else if (isa<PackExpansionTypeLoc>(TL)) {
1506 // The non-type template parameter pack's type is a pack expansion of types.
1507 // Determine whether we need to expand this parameter pack into separate
1508 // types.
1509 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1510 TypeLoc Pattern = Expansion.getPatternLoc();
1511 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1512 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1513
1514 // Determine whether the set of unexpanded parameter packs can and should
1515 // be expanded.
1516 bool Expand = true;
1517 bool RetainExpansion = false;
1518 llvm::Optional<unsigned> OrigNumExpansions
1519 = Expansion.getTypePtr()->getNumExpansions();
1520 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1521 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1522 Pattern.getSourceRange(),
1523 Unexpanded.data(),
1524 Unexpanded.size(),
1525 TemplateArgs,
1526 Expand, RetainExpansion,
1527 NumExpansions))
1528 return 0;
1529
1530 if (Expand) {
1531 for (unsigned I = 0; I != *NumExpansions; ++I) {
1532 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1533 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1534 D->getLocation(),
1535 D->getDeclName());
1536 if (!NewDI)
1537 return 0;
1538
1539 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1540 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1541 NewDI->getType(),
1542 D->getLocation());
1543 if (NewT.isNull())
1544 return 0;
1545 ExpandedParameterPackTypes.push_back(NewT);
1546 }
1547
1548 // Note that we have an expanded parameter pack. The "type" of this
1549 // expanded parameter pack is the original expansion type, but callers
1550 // will end up using the expanded parameter pack types for type-checking.
1551 IsExpandedParameterPack = true;
1552 DI = D->getTypeSourceInfo();
1553 T = DI->getType();
1554 } else {
1555 // We cannot fully expand the pack expansion now, so substitute into the
1556 // pattern and create a new pack expansion type.
1557 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1558 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1559 D->getLocation(),
1560 D->getDeclName());
1561 if (!NewPattern)
1562 return 0;
1563
1564 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1565 NumExpansions);
1566 if (!DI)
1567 return 0;
1568
1569 T = DI->getType();
1570 }
1571 } else {
1572 // Simple case: substitution into a parameter that is not a parameter pack.
1573 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1574 D->getLocation(), D->getDeclName());
1575 if (!DI)
1576 return 0;
1577
1578 // Check that this type is acceptable for a non-type template parameter.
1579 bool Invalid = false;
1580 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1581 D->getLocation());
1582 if (T.isNull()) {
1583 T = SemaRef.Context.IntTy;
1584 Invalid = true;
1585 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001586 }
1587
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001588 NonTypeTemplateParmDecl *Param;
1589 if (IsExpandedParameterPack)
1590 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1591 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001592 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001593 D->getPosition(),
1594 D->getIdentifier(), T,
1595 DI,
1596 ExpandedParameterPackTypes.data(),
1597 ExpandedParameterPackTypes.size(),
1598 ExpandedParameterPackTypesAsWritten.data());
1599 else
1600 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1601 D->getLocation(),
1602 D->getDepth() - TemplateArgs.getNumLevels(),
1603 D->getPosition(),
1604 D->getIdentifier(), T,
1605 D->isParameterPack(), DI);
1606
Douglas Gregor9a299e02011-03-04 17:52:15 +00001607 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001608 if (Invalid)
1609 Param->setInvalidDecl();
1610
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001611 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001612
1613 // Introduce this template parameter's instantiation into the instantiation
1614 // scope.
1615 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001616 return Param;
1617}
1618
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001619Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001620TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1621 TemplateTemplateParmDecl *D) {
1622 // Instantiate the template parameter list of the template template parameter.
1623 TemplateParameterList *TempParams = D->getTemplateParameters();
1624 TemplateParameterList *InstParams;
1625 {
1626 // Perform the actual substitution of template parameters within a new,
1627 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001628 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001629 InstParams = SubstTemplateParams(TempParams);
1630 if (!InstParams)
1631 return NULL;
1632 }
1633
1634 // Build the template template parameter.
1635 TemplateTemplateParmDecl *Param
1636 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001637 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001638 D->getPosition(), D->isParameterPack(),
1639 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001640 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001641 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001642
Douglas Gregor9106ef72009-11-11 16:58:32 +00001643 // Introduce this template parameter's instantiation into the instantiation
1644 // scope.
1645 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1646
1647 return Param;
1648}
1649
Douglas Gregor48c32a72009-11-17 06:07:40 +00001650Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001651 // Using directives are never dependent (and never contain any types or
1652 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001653
1654 UsingDirectiveDecl *Inst
1655 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1656 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001657 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001658 D->getIdentLocation(),
1659 D->getNominatedNamespace(),
1660 D->getCommonAncestor());
1661 Owner->addDecl(Inst);
1662 return Inst;
1663}
1664
John McCalled976492009-12-04 22:46:56 +00001665Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001666
1667 // The nested name specifier may be dependent, for example
1668 // template <typename T> struct t {
1669 // struct s1 { T f1(); };
1670 // struct s2 : s1 { using s1::f1; };
1671 // };
1672 // template struct t<int>;
1673 // Here, in using s1::f1, s1 refers to t<T>::s1;
1674 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001675 NestedNameSpecifierLoc QualifierLoc
1676 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1677 TemplateArgs);
1678 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001679 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001680
1681 // The name info is non-dependent, so no transformation
1682 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001683 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001684
John McCall9f54ad42009-12-10 09:41:52 +00001685 // We only need to do redeclaration lookups if we're in a class
1686 // scope (in fact, it's not really even possible in non-class
1687 // scopes).
1688 bool CheckRedeclaration = Owner->isRecord();
1689
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001690 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1691 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001692
John McCalled976492009-12-04 22:46:56 +00001693 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001694 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001695 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001696 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001697 D->isTypeName());
1698
Douglas Gregor5149f372011-02-25 15:54:31 +00001699 CXXScopeSpec SS;
1700 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001701 if (CheckRedeclaration) {
1702 Prev.setHideTags(false);
1703 SemaRef.LookupQualifiedName(Prev, Owner);
1704
1705 // Check for invalid redeclarations.
1706 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1707 D->isTypeName(), SS,
1708 D->getLocation(), Prev))
1709 NewUD->setInvalidDecl();
1710
1711 }
1712
1713 if (!NewUD->isInvalidDecl() &&
1714 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001715 D->getLocation()))
1716 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001717
John McCalled976492009-12-04 22:46:56 +00001718 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1719 NewUD->setAccess(D->getAccess());
1720 Owner->addDecl(NewUD);
1721
John McCall9f54ad42009-12-10 09:41:52 +00001722 // Don't process the shadow decls for an invalid decl.
1723 if (NewUD->isInvalidDecl())
1724 return NewUD;
1725
John McCall323c3102009-12-22 22:26:37 +00001726 bool isFunctionScope = Owner->isFunctionOrMethod();
1727
John McCall9f54ad42009-12-10 09:41:52 +00001728 // Process the shadow decls.
1729 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1730 I != E; ++I) {
1731 UsingShadowDecl *Shadow = *I;
1732 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001733 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1734 Shadow->getLocation(),
1735 Shadow->getTargetDecl(),
1736 TemplateArgs));
1737 if (!InstTarget)
1738 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001739
1740 if (CheckRedeclaration &&
1741 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1742 continue;
1743
1744 UsingShadowDecl *InstShadow
1745 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1746 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001747
1748 if (isFunctionScope)
1749 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001750 }
John McCalled976492009-12-04 22:46:56 +00001751
1752 return NewUD;
1753}
1754
1755Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001756 // Ignore these; we handle them in bulk when processing the UsingDecl.
1757 return 0;
John McCalled976492009-12-04 22:46:56 +00001758}
1759
John McCall7ba107a2009-11-18 02:36:19 +00001760Decl * TemplateDeclInstantiator
1761 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001762 NestedNameSpecifierLoc QualifierLoc
1763 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1764 TemplateArgs);
1765 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001766 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001768 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001769 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001771 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1772 // Hence, no tranformation is required for it.
1773 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001774 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001775 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001776 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001777 /*instantiation*/ true,
1778 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001779 if (UD)
John McCalled976492009-12-04 22:46:56 +00001780 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1781
John McCall7ba107a2009-11-18 02:36:19 +00001782 return UD;
1783}
1784
1785Decl * TemplateDeclInstantiator
1786 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001787 NestedNameSpecifierLoc QualifierLoc
1788 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1789 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001790 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001791
John McCall7ba107a2009-11-18 02:36:19 +00001792 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001793 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001794
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001795 DeclarationNameInfo NameInfo
1796 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1797
John McCall7ba107a2009-11-18 02:36:19 +00001798 NamedDecl *UD =
1799 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001800 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001801 /*instantiation*/ true,
1802 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001803 if (UD)
John McCalled976492009-12-04 22:46:56 +00001804 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1805
Anders Carlsson0d8df782009-08-29 19:37:28 +00001806 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001807}
1808
John McCallce3ff2b2009-08-25 22:02:44 +00001809Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001810 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001811 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001812 if (D->isInvalidDecl())
1813 return 0;
1814
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001815 return Instantiator.Visit(D);
1816}
1817
John McCalle29ba202009-08-20 01:44:21 +00001818/// \brief Instantiates a nested template parameter list in the current
1819/// instantiation context.
1820///
1821/// \param L The parameter list to instantiate
1822///
1823/// \returns NULL if there was an error
1824TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001825TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001826 // Get errors for all the parameters before bailing out.
1827 bool Invalid = false;
1828
1829 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001830 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001831 ParamVector Params;
1832 Params.reserve(N);
1833 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1834 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001835 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001836 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001837 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001838 }
1839
1840 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001841 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001842 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001843
1844 TemplateParameterList *InstL
1845 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1846 L->getLAngleLoc(), &Params.front(), N,
1847 L->getRAngleLoc());
1848 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001849}
John McCalle29ba202009-08-20 01:44:21 +00001850
Douglas Gregored9c0f92009-10-29 00:04:11 +00001851/// \brief Instantiate the declaration of a class template partial
1852/// specialization.
1853///
1854/// \param ClassTemplate the (instantiated) class template that is partially
1855// specialized by the instantiation of \p PartialSpec.
1856///
1857/// \param PartialSpec the (uninstantiated) class template partial
1858/// specialization that we are instantiating.
1859///
Douglas Gregord65587f2010-11-10 19:44:59 +00001860/// \returns The instantiated partial specialization, if successful; otherwise,
1861/// NULL to indicate an error.
1862ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001863TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1864 ClassTemplateDecl *ClassTemplate,
1865 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001866 // Create a local instantiation scope for this class template partial
1867 // specialization, which will contain the instantiations of the template
1868 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001869 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001870
Douglas Gregored9c0f92009-10-29 00:04:11 +00001871 // Substitute into the template parameters of the class template partial
1872 // specialization.
1873 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1874 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1875 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001876 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001877
1878 // Substitute into the template arguments of the class template partial
1879 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001880 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001881 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1882 PartialSpec->getNumTemplateArgsAsWritten(),
1883 InstTemplateArgs, TemplateArgs))
1884 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001885
Douglas Gregored9c0f92009-10-29 00:04:11 +00001886 // Check that the template argument list is well-formed for this
1887 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001888 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001889 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1890 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001891 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001892 false,
1893 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001894 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001895
1896 // Figure out where to insert this class template partial specialization
1897 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001898 void *InsertPos = 0;
1899 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001900 = ClassTemplate->findPartialSpecialization(Converted.data(),
1901 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001902
1903 // Build the canonical type that describes the converted template
1904 // arguments of the class template partial specialization.
1905 QualType CanonType
1906 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001907 Converted.data(),
1908 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001909
1910 // Build the fully-sugared type for this class template
1911 // specialization as the user wrote in the specialization
1912 // itself. This means that we'll pretty-print the type retrieved
1913 // from the specialization's declaration the way that the user
1914 // actually wrote the specialization, rather than formatting the
1915 // name based on the "canonical" representation used to store the
1916 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001917 TypeSourceInfo *WrittenTy
1918 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1919 TemplateName(ClassTemplate),
1920 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001921 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001922 CanonType);
1923
1924 if (PrevDecl) {
1925 // We've already seen a partial specialization with the same template
1926 // parameters and template arguments. This can happen, for example, when
1927 // substituting the outer template arguments ends up causing two
1928 // class template partial specializations of a member class template
1929 // to have identical forms, e.g.,
1930 //
1931 // template<typename T, typename U>
1932 // struct Outer {
1933 // template<typename X, typename Y> struct Inner;
1934 // template<typename Y> struct Inner<T, Y>;
1935 // template<typename Y> struct Inner<U, Y>;
1936 // };
1937 //
1938 // Outer<int, int> outer; // error: the partial specializations of Inner
1939 // // have the same signature.
1940 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001941 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001942 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1943 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001944 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001945 }
1946
1947
1948 // Create the class template partial specialization declaration.
1949 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001950 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1951 PartialSpec->getTagKind(),
1952 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001953 PartialSpec->getLocation(),
1954 InstParams,
1955 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001956 Converted.data(),
1957 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001958 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001959 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001960 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001961 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001962 // Substitute the nested name specifier, if any.
1963 if (SubstQualifier(PartialSpec, InstPartialSpec))
1964 return 0;
1965
Douglas Gregored9c0f92009-10-29 00:04:11 +00001966 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001967 InstPartialSpec->setTypeAsWritten(WrittenTy);
1968
Douglas Gregored9c0f92009-10-29 00:04:11 +00001969 // Add this partial specialization to the set of class template partial
1970 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001971 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001972 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001973}
1974
John McCall21ef0fa2010-03-11 09:03:00 +00001975TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001976TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001977 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001978 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1979 assert(OldTInfo && "substituting function without type source info");
1980 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001981 TypeSourceInfo *NewTInfo
1982 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1983 D->getTypeSpecStartLoc(),
1984 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001985 if (!NewTInfo)
1986 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001987
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001988 if (NewTInfo != OldTInfo) {
1989 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001990 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001991 if (FunctionProtoTypeLoc *OldProtoLoc
1992 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001993 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001994 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1995 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001996 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
1997 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
1998 OldIdx != NumOldParams; ++OldIdx) {
1999 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2000 if (!OldParam->isParameterPack() ||
2001 (NewIdx < NumNewParams &&
2002 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2003 // Simple case: normal parameter, or a parameter pack that's
2004 // instantiated to a (still-dependent) parameter pack.
2005 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2006 Params.push_back(NewParam);
2007 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2008 NewParam);
2009 continue;
2010 }
2011
2012 // Parameter pack: make the instantiation an argument pack.
2013 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2014 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002015 unsigned NumArgumentsInExpansion
2016 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2017 TemplateArgs);
2018 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002019 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2020 Params.push_back(NewParam);
2021 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2022 NewParam);
2023 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002024 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002025 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002026 } else {
2027 // The function type itself was not dependent and therefore no
2028 // substitution occurred. However, we still need to instantiate
2029 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002030 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002031 if (FunctionProtoTypeLoc *OldProtoLoc
2032 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2033 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2034 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2035 if (!Parm)
2036 return 0;
2037 Params.push_back(Parm);
2038 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002039 }
2040 }
John McCall21ef0fa2010-03-11 09:03:00 +00002041 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002042}
2043
Mike Stump1eb44332009-09-09 15:08:12 +00002044/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002045/// declaration (New) from the corresponding fields of its template (Tmpl).
2046///
2047/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002048bool
2049TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002050 FunctionDecl *Tmpl) {
2051 if (Tmpl->isDeleted())
2052 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregorcca9e962009-07-01 22:01:06 +00002054 // If we are performing substituting explicitly-specified template arguments
2055 // or deduced template arguments into a function template and we reach this
2056 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002057 // to keeping the new function template specialization. We therefore
2058 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002059 // into a template instantiation for this specific function template
2060 // specialization, which is not a SFINAE context, so that we diagnose any
2061 // further errors in the declaration itself.
2062 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2063 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2064 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2065 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002066 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002067 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002068 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002069 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002070 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002071 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2072 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002073 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002074 }
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002077 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2078 assert(Proto && "Function template without prototype?");
2079
2080 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
2081 Proto->getNoReturnAttr()) {
2082 // The function has an exception specification or a "noreturn"
2083 // attribute. Substitute into each of the exception types.
2084 llvm::SmallVector<QualType, 4> Exceptions;
2085 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2086 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002087 if (const PackExpansionType *PackExpansion
2088 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2089 // We have a pack expansion. Instantiate it.
2090 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2091 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2092 Unexpanded);
2093 assert(!Unexpanded.empty() &&
2094 "Pack expansion without parameter packs?");
2095
2096 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002097 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002098 llvm::Optional<unsigned> NumExpansions
2099 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002100 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2101 SourceRange(),
2102 Unexpanded.data(),
2103 Unexpanded.size(),
2104 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002105 Expand,
2106 RetainExpansion,
2107 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002108 break;
2109
2110 if (!Expand) {
2111 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002112 // just substitute into the pattern and create a new pack expansion
2113 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002114 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2115 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2116 TemplateArgs,
2117 New->getLocation(), New->getDeclName());
2118 if (T.isNull())
2119 break;
2120
Douglas Gregorcded4f62011-01-14 17:04:44 +00002121 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002122 Exceptions.push_back(T);
2123 continue;
2124 }
2125
2126 // Substitute into the pack expansion pattern for each template
2127 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002128 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2130
2131 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2132 TemplateArgs,
2133 New->getLocation(), New->getDeclName());
2134 if (T.isNull()) {
2135 Invalid = true;
2136 break;
2137 }
2138
2139 Exceptions.push_back(T);
2140 }
2141
2142 if (Invalid)
2143 break;
2144
2145 continue;
2146 }
2147
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002148 QualType T
2149 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2150 New->getLocation(), New->getDeclName());
2151 if (T.isNull() ||
2152 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2153 continue;
2154
2155 Exceptions.push_back(T);
2156 }
2157
2158 // Rebuild the function type
2159
John McCalle23cf432010-12-14 08:05:40 +00002160 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002161 EPI.ExceptionSpecType = Proto->hasExceptionSpec() ?
2162 (Proto->hasAnyExceptionSpec() ? EST_DynamicAny : EST_Dynamic) :
2163 EST_None;
John McCalle23cf432010-12-14 08:05:40 +00002164 EPI.NumExceptions = Exceptions.size();
2165 EPI.Exceptions = Exceptions.data();
2166 EPI.ExtInfo = Proto->getExtInfo();
2167
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002168 const FunctionProtoType *NewProto
2169 = New->getType()->getAs<FunctionProtoType>();
2170 assert(NewProto && "Template instantiation without function prototype?");
2171 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2172 NewProto->arg_type_begin(),
2173 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002174 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002175 }
2176
John McCall1d8d1cc2010-08-01 02:01:53 +00002177 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002178
Douglas Gregore53060f2009-06-25 22:08:12 +00002179 return false;
2180}
2181
Douglas Gregor5545e162009-03-24 00:38:23 +00002182/// \brief Initializes common fields of an instantiated method
2183/// declaration (New) from the corresponding fields of its template
2184/// (Tmpl).
2185///
2186/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002187bool
2188TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002189 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002190 if (InitFunctionInstantiation(New, Tmpl))
2191 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Douglas Gregor5545e162009-03-24 00:38:23 +00002193 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002194 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002195 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002196
2197 // FIXME: attributes
2198 // FIXME: New needs a pointer to Tmpl
2199 return false;
2200}
Douglas Gregora58861f2009-05-13 20:28:22 +00002201
2202/// \brief Instantiate the definition of the given function from its
2203/// template.
2204///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002205/// \param PointOfInstantiation the point at which the instantiation was
2206/// required. Note that this is not precisely a "point of instantiation"
2207/// for the function, but it's close.
2208///
Douglas Gregora58861f2009-05-13 20:28:22 +00002209/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002210/// function template specialization or member function of a class template
2211/// specialization.
2212///
2213/// \param Recursive if true, recursively instantiates any functions that
2214/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002215///
2216/// \param DefinitionRequired if true, then we are performing an explicit
2217/// instantiation where the body of the function is required. Complain if
2218/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002219void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002220 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002221 bool Recursive,
2222 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002223 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002224 return;
2225
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002226 // Never instantiate an explicit specialization.
2227 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2228 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002229
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002230 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002231 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002232 Stmt *Pattern = 0;
2233 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002234 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002235
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002236 if (!Pattern) {
2237 if (DefinitionRequired) {
2238 if (Function->getPrimaryTemplate())
2239 Diag(PointOfInstantiation,
2240 diag::err_explicit_instantiation_undefined_func_template)
2241 << Function->getPrimaryTemplate();
2242 else
2243 Diag(PointOfInstantiation,
2244 diag::err_explicit_instantiation_undefined_member)
2245 << 1 << Function->getDeclName() << Function->getDeclContext();
2246
2247 if (PatternDecl)
2248 Diag(PatternDecl->getLocation(),
2249 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002250 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002251 } else if (Function->getTemplateSpecializationKind()
2252 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002253 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002254 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002255 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002256
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002257 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002258 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002259
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002260 // C++0x [temp.explicit]p9:
2261 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002262 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002263 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002264 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002265 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002266 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002267 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002269 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2270 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002271 return;
2272
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002273 // If we're performing recursive template instantiation, create our own
2274 // queue of pending implicit instantiations that we will instantiate later,
2275 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002276 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002277 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002278 if (Recursive) {
2279 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002280 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002281 }
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Douglas Gregor9679caf2010-05-12 17:27:19 +00002283 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002284 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002285 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002286
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002287 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002288 // recorded, unless we're actually a member function within a local
2289 // class, in which case we need to merge our results with the parent
2290 // scope (of the enclosing function).
2291 bool MergeWithParentScope = false;
2292 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2293 MergeWithParentScope = Rec->isLocalClass();
2294
2295 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002297 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002298 // instantiation scope, and set the parameter names to those used
2299 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002300 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002301 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2302 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002303 if (!PatternParam->isParameterPack()) {
2304 // Simple case: not a parameter pack.
2305 assert(FParamIdx < Function->getNumParams());
2306 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2307 FunctionParam->setDeclName(PatternParam->getDeclName());
2308 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2309 ++FParamIdx;
2310 continue;
2311 }
2312
2313 // Expand the parameter pack.
2314 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2315 for (unsigned NumFParams = Function->getNumParams();
2316 FParamIdx < NumFParams;
2317 ++FParamIdx) {
2318 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2319 FunctionParam->setDeclName(PatternParam->getDeclName());
2320 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2321 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002322 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002323
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002324 // Enter the scope of this instantiation. We don't use
2325 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002326 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002327
Mike Stump1eb44332009-09-09 15:08:12 +00002328 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002329 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002330
2331 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002332 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002333 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2334 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2335 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002336 }
2337
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002338 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002339 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002340
Douglas Gregor52604ab2009-09-11 21:19:12 +00002341 if (Body.isInvalid())
2342 Function->setInvalidDecl();
2343
John McCall9ae2f072010-08-23 23:25:46 +00002344 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002345 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002346
John McCall0c01d182010-03-24 05:22:00 +00002347 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2348
John McCalleee1d542011-02-14 07:13:47 +00002349 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002350
2351 DeclGroupRef DG(Function);
2352 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor60406be2010-01-16 22:29:39 +00002354 // This class may have local implicit instantiations that need to be
2355 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002356 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002357 Scope.Exit();
2358
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002359 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002360 // Define any pending vtables.
2361 DefineUsedVTables();
2362
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002363 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002364 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002365 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002367 // Restore the set of pending vtables.
2368 VTableUses.swap(SavedVTableUses);
2369
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002370 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002371 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002372 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002373}
2374
2375/// \brief Instantiate the definition of the given variable from its
2376/// template.
2377///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002378/// \param PointOfInstantiation the point at which the instantiation was
2379/// required. Note that this is not precisely a "point of instantiation"
2380/// for the function, but it's close.
2381///
2382/// \param Var the already-instantiated declaration of a static member
2383/// variable of a class template specialization.
2384///
2385/// \param Recursive if true, recursively instantiates any functions that
2386/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002387///
2388/// \param DefinitionRequired if true, then we are performing an explicit
2389/// instantiation where an out-of-line definition of the member variable
2390/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002391void Sema::InstantiateStaticDataMemberDefinition(
2392 SourceLocation PointOfInstantiation,
2393 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002394 bool Recursive,
2395 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002396 if (Var->isInvalidDecl())
2397 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregor7caa6822009-07-24 20:34:43 +00002399 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002400 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002401 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002402 assert(Def->isStaticDataMember() && "Not a static data member?");
2403 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregor0d035142009-10-27 18:42:08 +00002405 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002406 // We did not find an out-of-line definition of this static data member,
2407 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002408 // instantiate this definition (or provide a specialization for it) in
2409 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002410 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002411 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002412 Diag(PointOfInstantiation,
2413 diag::err_explicit_instantiation_undefined_member)
2414 << 2 << Var->getDeclName() << Var->getDeclContext();
2415 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002416 } else if (Var->getTemplateSpecializationKind()
2417 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002418 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002419 std::make_pair(Var, PointOfInstantiation));
2420 }
2421
Douglas Gregor7caa6822009-07-24 20:34:43 +00002422 return;
2423 }
2424
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002425 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002426 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002427 return;
2428
2429 // C++0x [temp.explicit]p9:
2430 // Except for inline functions, other explicit instantiation declarations
2431 // have the effect of suppressing the implicit instantiation of the entity
2432 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002433 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002434 == TSK_ExplicitInstantiationDeclaration)
2435 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Douglas Gregor7caa6822009-07-24 20:34:43 +00002437 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2438 if (Inst)
2439 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002440
Douglas Gregor7caa6822009-07-24 20:34:43 +00002441 // If we're performing recursive template instantiation, create our own
2442 // queue of pending implicit instantiations that we will instantiate later,
2443 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002444 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002445 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002446 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Douglas Gregor7caa6822009-07-24 20:34:43 +00002448 // Enter the scope of this instantiation. We don't use
2449 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002450 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002452 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002453 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002454 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002455
2456 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002457
2458 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002459 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2460 assert(MSInfo && "Missing member specialization information?");
2461 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2462 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002463 DeclGroupRef DG(Var);
2464 Consumer.HandleTopLevelDecl(DG);
2465 }
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Douglas Gregor7caa6822009-07-24 20:34:43 +00002467 if (Recursive) {
2468 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002469 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002470 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Douglas Gregor7caa6822009-07-24 20:34:43 +00002472 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002473 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002474 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002475}
Douglas Gregor815215d2009-05-27 05:35:12 +00002476
Anders Carlsson09025312009-08-29 05:16:22 +00002477void
2478Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2479 const CXXConstructorDecl *Tmpl,
2480 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Anders Carlsson09025312009-08-29 05:16:22 +00002482 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002483 bool AnyErrors = false;
2484
Anders Carlsson09025312009-08-29 05:16:22 +00002485 // Instantiate all the initializers.
2486 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002487 InitsEnd = Tmpl->init_end();
2488 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002489 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002490
Chandler Carruth030ef472010-09-03 21:54:20 +00002491 // Only instantiate written initializers, let Sema re-construct implicit
2492 // ones.
2493 if (!Init->isWritten())
2494 continue;
2495
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002496 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002497 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002499 SourceLocation EllipsisLoc;
2500
2501 if (Init->isPackExpansion()) {
2502 // This is a pack expansion. We should expand it now.
2503 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2504 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2505 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2506 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002507 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002508 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002509 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2510 BaseTL.getSourceRange(),
2511 Unexpanded.data(),
2512 Unexpanded.size(),
2513 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002514 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002515 NumExpansions)) {
2516 AnyErrors = true;
2517 New->setInvalidDecl();
2518 continue;
2519 }
2520 assert(ShouldExpand && "Partial instantiation of base initializer?");
2521
2522 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002523 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002524 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2525
2526 // Instantiate the initializer.
2527 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2528 LParenLoc, NewArgs, RParenLoc)) {
2529 AnyErrors = true;
2530 break;
2531 }
2532
2533 // Instantiate the base type.
2534 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2535 TemplateArgs,
2536 Init->getSourceLocation(),
2537 New->getDeclName());
2538 if (!BaseTInfo) {
2539 AnyErrors = true;
2540 break;
2541 }
2542
2543 // Build the initializer.
2544 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2545 BaseTInfo,
2546 (Expr **)NewArgs.data(),
2547 NewArgs.size(),
2548 Init->getLParenLoc(),
2549 Init->getRParenLoc(),
2550 New->getParent(),
2551 SourceLocation());
2552 if (NewInit.isInvalid()) {
2553 AnyErrors = true;
2554 break;
2555 }
2556
2557 NewInits.push_back(NewInit.get());
2558 NewArgs.clear();
2559 }
2560
2561 continue;
2562 }
2563
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002564 // Instantiate the initializer.
2565 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002566 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002567 AnyErrors = true;
2568 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002569 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002570
Anders Carlsson09025312009-08-29 05:16:22 +00002571 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002572 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002573 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002574 TemplateArgs,
2575 Init->getSourceLocation(),
2576 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002577 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002578 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002579 New->setInvalidDecl();
2580 continue;
2581 }
2582
John McCalla93c9342009-12-07 02:54:59 +00002583 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002584 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002585 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002586 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002587 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002588 New->getParent(),
2589 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002590 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002591 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002592 Init->getMemberLocation(),
2593 Init->getMember(),
2594 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002595 if (!Member) {
2596 AnyErrors = true;
2597 New->setInvalidDecl();
2598 continue;
2599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
2601 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002602 NewArgs.size(),
2603 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002604 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002605 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002606 } else if (Init->isIndirectMemberInitializer()) {
2607 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002608 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002609 Init->getMemberLocation(),
2610 Init->getIndirectMember(), TemplateArgs));
2611
Douglas Gregorb7107222011-03-04 19:46:35 +00002612 if (!IndirectMember) {
2613 AnyErrors = true;
2614 New->setInvalidDecl();
2615 continue;
2616 }
2617
Francois Pichet00eb3f92010-12-04 09:14:42 +00002618 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2619 NewArgs.size(),
2620 Init->getSourceLocation(),
2621 Init->getLParenLoc(),
2622 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002623 }
2624
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002625 if (NewInit.isInvalid()) {
2626 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002627 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002628 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002629 // FIXME: It would be nice if ASTOwningVector had a release function.
2630 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Anders Carlsson09025312009-08-29 05:16:22 +00002632 NewInits.push_back((MemInitTy *)NewInit.get());
2633 }
2634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Anders Carlsson09025312009-08-29 05:16:22 +00002636 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002637 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002638 /*FIXME: ColonLoc */
2639 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002640 NewInits.data(), NewInits.size(),
2641 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002642}
2643
John McCall52a575a2009-08-29 08:11:13 +00002644// TODO: this could be templated if the various decl types used the
2645// same method name.
2646static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2647 ClassTemplateDecl *Instance) {
2648 Pattern = Pattern->getCanonicalDecl();
2649
2650 do {
2651 Instance = Instance->getCanonicalDecl();
2652 if (Pattern == Instance) return true;
2653 Instance = Instance->getInstantiatedFromMemberTemplate();
2654 } while (Instance);
2655
2656 return false;
2657}
2658
Douglas Gregor0d696532009-09-28 06:34:35 +00002659static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2660 FunctionTemplateDecl *Instance) {
2661 Pattern = Pattern->getCanonicalDecl();
2662
2663 do {
2664 Instance = Instance->getCanonicalDecl();
2665 if (Pattern == Instance) return true;
2666 Instance = Instance->getInstantiatedFromMemberTemplate();
2667 } while (Instance);
2668
2669 return false;
2670}
2671
Douglas Gregored9c0f92009-10-29 00:04:11 +00002672static bool
2673isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2674 ClassTemplatePartialSpecializationDecl *Instance) {
2675 Pattern
2676 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2677 do {
2678 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2679 Instance->getCanonicalDecl());
2680 if (Pattern == Instance)
2681 return true;
2682 Instance = Instance->getInstantiatedFromMember();
2683 } while (Instance);
2684
2685 return false;
2686}
2687
John McCall52a575a2009-08-29 08:11:13 +00002688static bool isInstantiationOf(CXXRecordDecl *Pattern,
2689 CXXRecordDecl *Instance) {
2690 Pattern = Pattern->getCanonicalDecl();
2691
2692 do {
2693 Instance = Instance->getCanonicalDecl();
2694 if (Pattern == Instance) return true;
2695 Instance = Instance->getInstantiatedFromMemberClass();
2696 } while (Instance);
2697
2698 return false;
2699}
2700
2701static bool isInstantiationOf(FunctionDecl *Pattern,
2702 FunctionDecl *Instance) {
2703 Pattern = Pattern->getCanonicalDecl();
2704
2705 do {
2706 Instance = Instance->getCanonicalDecl();
2707 if (Pattern == Instance) return true;
2708 Instance = Instance->getInstantiatedFromMemberFunction();
2709 } while (Instance);
2710
2711 return false;
2712}
2713
2714static bool isInstantiationOf(EnumDecl *Pattern,
2715 EnumDecl *Instance) {
2716 Pattern = Pattern->getCanonicalDecl();
2717
2718 do {
2719 Instance = Instance->getCanonicalDecl();
2720 if (Pattern == Instance) return true;
2721 Instance = Instance->getInstantiatedFromMemberEnum();
2722 } while (Instance);
2723
2724 return false;
2725}
2726
John McCalled976492009-12-04 22:46:56 +00002727static bool isInstantiationOf(UsingShadowDecl *Pattern,
2728 UsingShadowDecl *Instance,
2729 ASTContext &C) {
2730 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2731}
2732
2733static bool isInstantiationOf(UsingDecl *Pattern,
2734 UsingDecl *Instance,
2735 ASTContext &C) {
2736 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2737}
2738
John McCall7ba107a2009-11-18 02:36:19 +00002739static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2740 UsingDecl *Instance,
2741 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002742 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002743}
2744
2745static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002746 UsingDecl *Instance,
2747 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002748 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002749}
2750
John McCall52a575a2009-08-29 08:11:13 +00002751static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2752 VarDecl *Instance) {
2753 assert(Instance->isStaticDataMember());
2754
2755 Pattern = Pattern->getCanonicalDecl();
2756
2757 do {
2758 Instance = Instance->getCanonicalDecl();
2759 if (Pattern == Instance) return true;
2760 Instance = Instance->getInstantiatedFromStaticDataMember();
2761 } while (Instance);
2762
2763 return false;
2764}
2765
John McCalled976492009-12-04 22:46:56 +00002766// Other is the prospective instantiation
2767// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002768static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002769 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002770 if (UnresolvedUsingTypenameDecl *UUD
2771 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2772 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2773 return isInstantiationOf(UUD, UD, Ctx);
2774 }
2775 }
2776
2777 if (UnresolvedUsingValueDecl *UUD
2778 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002779 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2780 return isInstantiationOf(UUD, UD, Ctx);
2781 }
2782 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002783
Anders Carlsson0d8df782009-08-29 19:37:28 +00002784 return false;
2785 }
Mike Stump1eb44332009-09-09 15:08:12 +00002786
John McCall52a575a2009-08-29 08:11:13 +00002787 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2788 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002789
John McCall52a575a2009-08-29 08:11:13 +00002790 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2791 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002792
John McCall52a575a2009-08-29 08:11:13 +00002793 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2794 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002795
Douglas Gregor7caa6822009-07-24 20:34:43 +00002796 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002797 if (Var->isStaticDataMember())
2798 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2799
2800 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2801 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002802
Douglas Gregor0d696532009-09-28 06:34:35 +00002803 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2804 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2805
Douglas Gregored9c0f92009-10-29 00:04:11 +00002806 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2807 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2808 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2809 PartialSpec);
2810
Anders Carlssond8b285f2009-09-01 04:26:58 +00002811 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2812 if (!Field->getDeclName()) {
2813 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002814 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002815 cast<FieldDecl>(D);
2816 }
2817 }
Mike Stump1eb44332009-09-09 15:08:12 +00002818
John McCalled976492009-12-04 22:46:56 +00002819 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2820 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2821
2822 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2823 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2824
Douglas Gregor815215d2009-05-27 05:35:12 +00002825 return D->getDeclName() && isa<NamedDecl>(Other) &&
2826 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2827}
2828
2829template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002830static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002831 NamedDecl *D,
2832 ForwardIterator first,
2833 ForwardIterator last) {
2834 for (; first != last; ++first)
2835 if (isInstantiationOf(Ctx, D, *first))
2836 return cast<NamedDecl>(*first);
2837
2838 return 0;
2839}
2840
John McCall02cace72009-08-28 07:59:38 +00002841/// \brief Finds the instantiation of the given declaration context
2842/// within the current instantiation.
2843///
2844/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002845DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002846 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002847 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002848 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002849 return cast_or_null<DeclContext>(ID);
2850 } else return DC;
2851}
2852
Douglas Gregored961e72009-05-27 17:54:46 +00002853/// \brief Find the instantiation of the given declaration within the
2854/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002855///
2856/// This routine is intended to be used when \p D is a declaration
2857/// referenced from within a template, that needs to mapped into the
2858/// corresponding declaration within an instantiation. For example,
2859/// given:
2860///
2861/// \code
2862/// template<typename T>
2863/// struct X {
2864/// enum Kind {
2865/// KnownValue = sizeof(T)
2866/// };
2867///
2868/// bool getKind() const { return KnownValue; }
2869/// };
2870///
2871/// template struct X<int>;
2872/// \endcode
2873///
2874/// In the instantiation of X<int>::getKind(), we need to map the
2875/// EnumConstantDecl for KnownValue (which refers to
2876/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002877/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2878/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002879NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002880 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002881 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002882 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002883 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002884 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002885 // D is a local of some kind. Look into the map of local
2886 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002887 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2888 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2889 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002890
Chris Lattner57ad3782011-02-17 20:34:02 +00002891 if (Found) {
2892 if (Decl *FD = Found->dyn_cast<Decl *>())
2893 return cast<NamedDecl>(FD);
2894
2895 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2896 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2897 }
2898
2899 // If we didn't find the decl, then we must have a label decl that hasn't
2900 // been found yet. Lazily instantiate it and return it now.
2901 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002902
Chris Lattner57ad3782011-02-17 20:34:02 +00002903 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2904 assert(Inst && "Failed to instantiate label??");
2905
2906 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2907 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002908 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002909
Douglas Gregore95b4092009-09-16 18:34:49 +00002910 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2911 if (!Record->isDependentContext())
2912 return D;
2913
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002914 // If the RecordDecl is actually the injected-class-name or a
2915 // "templated" declaration for a class template, class template
2916 // partial specialization, or a member class of a class template,
2917 // substitute into the injected-class-name of the class template
2918 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002919 QualType T;
2920 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2921
2922 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002923 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002924 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2925 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002926 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002927
2928 // If we call SubstType with an InjectedClassNameType here we
2929 // can end up in an infinite loop.
2930 T = Context.getTypeDeclType(Record);
2931 assert(isa<InjectedClassNameType>(T) &&
2932 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002933 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002934 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002935
2936 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002937 // Substitute into the injected-class-name to get the type
2938 // corresponding to the instantiation we want, which may also be
2939 // the current instantiation (if we're in a template
2940 // definition). This substitution should never fail, since we
2941 // know we can instantiate the injected-class-name or we
2942 // wouldn't have gotten to the injected-class-name!
2943
2944 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2945 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00002946 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00002947 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2948
2949 if (!T->isDependentType()) {
2950 assert(T->isRecordType() && "Instantiation must produce a record type");
2951 return T->getAs<RecordType>()->getDecl();
2952 }
2953
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002954 // We are performing "partial" template instantiation to create
2955 // the member declarations for the members of a class template
2956 // specialization. Therefore, D is actually referring to something
2957 // in the current instantiation. Look through the current
2958 // context, which contains actual instantiations, to find the
2959 // instantiation of the "current instantiation" that D refers
2960 // to.
2961 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002962 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002963 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002964 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002965 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002966 if (isInstantiationOf(ClassTemplate,
2967 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002968 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002969
2970 if (!DC->isDependentContext())
2971 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002972 }
2973
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002974 // We're performing "instantiation" of a member of the current
2975 // instantiation while we are type-checking the
2976 // definition. Compute the declaration context and return that.
2977 assert(!SawNonDependentContext &&
2978 "No dependent context while instantiating record");
2979 DeclContext *DC = computeDeclContext(T);
2980 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002981 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002982 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002983 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002984
Douglas Gregore95b4092009-09-16 18:34:49 +00002985 // Fall through to deal with other dependent record types (e.g.,
2986 // anonymous unions in class templates).
2987 }
John McCall52a575a2009-08-29 08:11:13 +00002988
Douglas Gregore95b4092009-09-16 18:34:49 +00002989 if (!ParentDC->isDependentContext())
2990 return D;
2991
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002992 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002993 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002994 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Douglas Gregor815215d2009-05-27 05:35:12 +00002996 if (ParentDC != D->getDeclContext()) {
2997 // We performed some kind of instantiation in the parent context,
2998 // so now we need to look into the instantiated parent context to
2999 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003000
John McCall3cb0ebd2010-03-10 03:28:59 +00003001 // If our context used to be dependent, we may need to instantiate
3002 // it before performing lookup into that context.
3003 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003004 if (!Spec->isDependentContext()) {
3005 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003006 const RecordType *Tag = T->getAs<RecordType>();
3007 assert(Tag && "type of non-dependent record is not a RecordType");
3008 if (!Tag->isBeingDefined() &&
3009 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3010 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003011
3012 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003013 }
3014 }
3015
Douglas Gregor815215d2009-05-27 05:35:12 +00003016 NamedDecl *Result = 0;
3017 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003018 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003019 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3020 } else {
3021 // Since we don't have a name for the entity we're looking for,
3022 // our only option is to walk through all of the declarations to
3023 // find that name. This will occur in a few cases:
3024 //
3025 // - anonymous struct/union within a template
3026 // - unnamed class/struct/union/enum within a template
3027 //
3028 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003029 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003030 ParentDC->decls_begin(),
3031 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003032 }
Mike Stump1eb44332009-09-09 15:08:12 +00003033
John McCall9f54ad42009-12-10 09:41:52 +00003034 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregora93fc9f2011-03-04 20:42:52 +00003035 // Note: this assertion end up firing in invalid code even when none of the
3036 // AST invariants have been broken, so we explicitly check whether any
3037 // errors have been emitted
3038 assert((Result || isa<UsingShadowDecl>(D) || Diags.hasErrorOccurred()) &&
3039 "Unable to find instantiation of declaration!");
John McCall9f54ad42009-12-10 09:41:52 +00003040
Douglas Gregor815215d2009-05-27 05:35:12 +00003041 D = Result;
3042 }
3043
Douglas Gregor815215d2009-05-27 05:35:12 +00003044 return D;
3045}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003046
Mike Stump1eb44332009-09-09 15:08:12 +00003047/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003048/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003049void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003050 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003051 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003052 PendingImplicitInstantiation Inst;
3053
3054 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003055 Inst = PendingInstantiations.front();
3056 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003057 } else {
3058 Inst = PendingLocalImplicitInstantiations.front();
3059 PendingLocalImplicitInstantiations.pop_front();
3060 }
Mike Stump1eb44332009-09-09 15:08:12 +00003061
Douglas Gregor7caa6822009-07-24 20:34:43 +00003062 // Instantiate function definitions
3063 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003064 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3065 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003066 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3067 TSK_ExplicitInstantiationDefinition;
3068 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3069 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003070 continue;
3071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Douglas Gregor7caa6822009-07-24 20:34:43 +00003073 // Instantiate static data member definitions.
3074 VarDecl *Var = cast<VarDecl>(Inst.first);
3075 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003076
Chandler Carruth291b4412010-02-13 10:17:50 +00003077 // Don't try to instantiate declarations if the most recent redeclaration
3078 // is invalid.
3079 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3080 continue;
3081
3082 // Check if the most recent declaration has changed the specialization kind
3083 // and removed the need for implicit instantiation.
3084 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3085 case TSK_Undeclared:
3086 assert(false && "Cannot instantitiate an undeclared specialization.");
3087 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003088 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003089 continue; // No longer need to instantiate this type.
3090 case TSK_ExplicitInstantiationDefinition:
3091 // We only need an instantiation if the pending instantiation *is* the
3092 // explicit instantiation.
3093 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003094 case TSK_ImplicitInstantiation:
3095 break;
3096 }
3097
John McCallf312b1e2010-08-26 23:41:50 +00003098 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3099 "instantiating static data member "
3100 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Chandler Carruth58e390e2010-08-25 08:27:02 +00003102 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3103 TSK_ExplicitInstantiationDefinition;
3104 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3105 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003106 }
3107}
John McCall0c01d182010-03-24 05:22:00 +00003108
3109void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3110 const MultiLevelTemplateArgumentList &TemplateArgs) {
3111 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3112 E = Pattern->ddiag_end(); I != E; ++I) {
3113 DependentDiagnostic *DD = *I;
3114
3115 switch (DD->getKind()) {
3116 case DependentDiagnostic::Access:
3117 HandleDependentAccessCheck(*DD, TemplateArgs);
3118 break;
3119 }
3120 }
3121}