blob: 2481bd004dca83120ab78867389f14f8e127ad97 [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
Richard Smith3e4c6c42011-05-05 21:57:07 +0000131Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
132 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000134 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000135 if (DI->getType()->isDependentType() ||
136 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000137 DI = SemaRef.SubstType(DI, TemplateArgs,
138 D->getLocation(), D->getDeclName());
139 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000141 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000143 } else {
144 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000148 TypedefNameDecl *Typedef;
149 if (IsTypeAlias)
150 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
151 D->getLocation(), D->getIdentifier(), DI);
152 else
153 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
154 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000155 if (Invalid)
156 Typedef->setInvalidDecl();
157
John McCallcde5a402011-02-01 08:20:08 +0000158 // If the old typedef was the name for linkage purposes of an anonymous
159 // tag decl, re-establish that relationship for the new typedef.
160 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
161 TagDecl *oldTag = oldTagType->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000162 if (oldTag->getTypedefNameForAnonDecl() == D) {
John McCallcde5a402011-02-01 08:20:08 +0000163 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000164 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
165 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000166 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000167 }
168
Richard Smith162e1c12011-04-15 14:24:37 +0000169 if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000170 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
171 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000172 if (!InstPrev)
173 return 0;
174
Richard Smith162e1c12011-04-15 14:24:37 +0000175 Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev));
John McCall5126fd02009-12-30 00:31:22 +0000176 }
177
John McCall1d8d1cc2010-08-01 02:01:53 +0000178 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000179
John McCall46460a62010-01-20 21:53:11 +0000180 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000182 return Typedef;
183}
184
Richard Smith162e1c12011-04-15 14:24:37 +0000185Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000186 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
187 Owner->addDecl(Typedef);
188 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000189}
190
191Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000192 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
193 Owner->addDecl(Typedef);
194 return Typedef;
195}
196
197Decl *
198TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
199 // Create a local instantiation scope for this type alias template, which
200 // will contain the instantiations of the template parameters.
201 LocalInstantiationScope Scope(SemaRef);
202
203 TemplateParameterList *TempParams = D->getTemplateParameters();
204 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
205 if (!InstParams)
206 return 0;
207
208 TypeAliasDecl *Pattern = D->getTemplatedDecl();
209
210 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
211 if (Pattern->getPreviousDeclaration()) {
212 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
213 if (Found.first != Found.second) {
214 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
215 }
216 }
217
218 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
219 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
220 if (!AliasInst)
221 return 0;
222
223 TypeAliasTemplateDecl *Inst
224 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
225 D->getDeclName(), InstParams, AliasInst);
226 if (PrevAliasTemplate)
227 Inst->setPreviousDeclaration(PrevAliasTemplate);
228
229 Inst->setAccess(D->getAccess());
230
231 if (!PrevAliasTemplate)
232 Inst->setInstantiatedFromMemberTemplate(D);
233
234 Owner->addDecl(Inst);
235
236 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000237}
238
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000239/// \brief Instantiate an initializer, breaking it into separate
240/// initialization arguments.
241///
242/// \param S The semantic analysis object.
243///
244/// \param Init The initializer to instantiate.
245///
246/// \param TemplateArgs Template arguments to be substituted into the
247/// initializer.
248///
249/// \param NewArgs Will be filled in with the instantiation arguments.
250///
251/// \returns true if an error occurred, false otherwise
252static bool InstantiateInitializer(Sema &S, Expr *Init,
253 const MultiLevelTemplateArgumentList &TemplateArgs,
254 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000255 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000256 SourceLocation &RParenLoc) {
257 NewArgs.clear();
258 LParenLoc = SourceLocation();
259 RParenLoc = SourceLocation();
260
261 if (!Init)
262 return false;
263
John McCall4765fa02010-12-06 08:20:24 +0000264 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000265 Init = ExprTemp->getSubExpr();
266
267 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
268 Init = Binder->getSubExpr();
269
270 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
271 Init = ICE->getSubExprAsWritten();
272
273 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
274 LParenLoc = ParenList->getLParenLoc();
275 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000276 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
277 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000278 }
279
280 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000281 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000282 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
283 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000284 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000285
Douglas Gregor28329e52010-03-24 21:22:47 +0000286 // FIXME: Fake locations!
287 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000288 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000289 return false;
290 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000291 }
292
John McCall60d7b3a2010-08-24 06:29:42 +0000293 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000294 if (Result.isInvalid())
295 return true;
296
297 NewArgs.push_back(Result.takeAs<Expr>());
298 return false;
299}
300
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000301Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000302 // If this is the variable for an anonymous struct or union,
303 // instantiate the anonymous struct/union type first.
304 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
305 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
306 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
307 return 0;
308
John McCallce3ff2b2009-08-25 22:02:44 +0000309 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000310 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000311 TemplateArgs,
312 D->getTypeSpecStartLoc(),
313 D->getDeclName());
314 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000315 return 0;
316
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000317 if (DI->getType()->isFunctionType()) {
318 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
319 << D->isStaticDataMember() << DI->getType();
320 return 0;
321 }
322
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000323 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000324 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000325 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000327 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000328 D->getStorageClass(),
329 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000330 Var->setThreadSpecified(D->isThreadSpecified());
331 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000332 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCallb6217662010-03-15 10:12:16 +0000334 // Substitute the nested name specifier, if any.
335 if (SubstQualifier(D, Var))
336 return 0;
337
Mike Stump1eb44332009-09-09 15:08:12 +0000338 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000339 // out-of-line, the instantiation will have the same lexical
340 // context (which will be a namespace scope) as the template.
341 if (D->isOutOfLine())
342 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000343
John McCall46460a62010-01-20 21:53:11 +0000344 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000345
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000346 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000347 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000348 Var->setReferenced(D->isReferenced());
349 }
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000350
Mike Stump390b4cc2009-05-16 07:39:55 +0000351 // FIXME: In theory, we could have a previous declaration for variables that
352 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000353 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000354 // FIXME: having to fake up a LookupResult is dumb.
355 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000356 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000357 if (D->isStaticDataMember())
358 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000359 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor7caa6822009-07-24 20:34:43 +0000361 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000362 if (!D->isStaticDataMember())
363 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000364 Owner->makeDeclVisibleInContext(Var);
365 } else {
366 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000367 if (Owner->isFunctionOrMethod())
368 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000369 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000370 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000371
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000372 // Link instantiations of static data members back to the template from
373 // which they were instantiated.
374 if (Var->isStaticDataMember())
375 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000376 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000377
Douglas Gregor60c93c92010-02-09 07:26:29 +0000378 if (Var->getAnyInitializer()) {
379 // We already have an initializer in the class.
380 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000381 if (Var->isStaticDataMember() && !D->isOutOfLine())
382 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
383 else
384 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
385
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000386 // Instantiate the initializer.
387 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000388 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000389 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000390 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000391 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000392 // Attach the initializer to the declaration, if we have one.
393 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000394 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000395 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000397 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000398 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000399 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000400 RParenLoc,
401 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000402 } else {
403 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000404 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000405 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000406 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000407 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000408 // FIXME: Not too happy about invalidating the declaration
409 // because of a bogus initializer.
410 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000411 }
412
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000414 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
415 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000416 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000417
Douglas Gregor5764f612010-05-08 23:05:03 +0000418 // Diagnose unused local variables.
419 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
420 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000421
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000422 return Var;
423}
424
Abramo Bagnara6206d532010-06-05 05:09:32 +0000425Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
426 AccessSpecDecl* AD
427 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
428 D->getAccessSpecifierLoc(), D->getColonLoc());
429 Owner->addHiddenDecl(AD);
430 return AD;
431}
432
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000433Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
434 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000435 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000436 if (DI->getType()->isDependentType() ||
437 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000438 DI = SemaRef.SubstType(DI, TemplateArgs,
439 D->getLocation(), D->getDeclName());
440 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000441 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000442 Invalid = true;
443 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444 // C++ [temp.arg.type]p3:
445 // If a declaration acquires a function type through a type
446 // dependent on a template-parameter and this causes a
447 // declaration that does not use the syntactic form of a
448 // function declarator to have function type, the program is
449 // ill-formed.
450 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000451 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000452 Invalid = true;
453 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000454 } else {
455 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
457
458 Expr *BitWidth = D->getBitWidth();
459 if (Invalid)
460 BitWidth = 0;
461 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000462 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000463 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
John McCall60d7b3a2010-08-24 06:29:42 +0000465 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000466 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000467 if (InstantiatedBitWidth.isInvalid()) {
468 Invalid = true;
469 BitWidth = 0;
470 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000471 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 }
473
John McCall07fb6be2009-10-22 23:33:21 +0000474 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
475 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000476 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000477 D->getLocation(),
478 D->isMutable(),
479 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000480 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 D->getAccess(),
482 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000483 if (!Field) {
484 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000485 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
John McCall1d8d1cc2010-08-01 02:01:53 +0000488 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000489
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000490 if (Invalid)
491 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000493 if (!Field->getDeclName()) {
494 // Keep track of where this decl came from.
495 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000496 }
497 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
498 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000499 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000500 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000503 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000504 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000505 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000506
507 return Field;
508}
509
Francois Pichet87c2e122010-11-21 06:08:52 +0000510Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
511 NamedDecl **NamedChain =
512 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
513
514 int i = 0;
515 for (IndirectFieldDecl::chain_iterator PI =
516 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000517 PI != PE; ++PI) {
518 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
519 TemplateArgs);
520 if (!Next)
521 return 0;
522
523 NamedChain[i++] = Next;
524 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000525
Francois Pichet40e17752010-12-09 10:07:54 +0000526 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000527 IndirectFieldDecl* IndirectField
528 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000529 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000530 NamedChain, D->getChainingSize());
531
532
533 IndirectField->setImplicit(D->isImplicit());
534 IndirectField->setAccess(D->getAccess());
535 Owner->addDecl(IndirectField);
536 return IndirectField;
537}
538
John McCall02cace72009-08-28 07:59:38 +0000539Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000540 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000541 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000542 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000543 TypeSourceInfo *InstTy;
544 // If this is an unsupported friend, don't bother substituting template
545 // arguments into it. The actual type referred to won't be used by any
546 // parts of Clang, and may not be valid for instantiating. Just use the
547 // same info for the instantiated friend.
548 if (D->isUnsupportedFriend()) {
549 InstTy = Ty;
550 } else {
551 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
552 D->getLocation(), DeclarationName());
553 }
554 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000555 return 0;
John McCall02cace72009-08-28 07:59:38 +0000556
Douglas Gregor06245bf2010-04-07 17:57:12 +0000557 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
558 if (!FD)
559 return 0;
560
561 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000562 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000563 Owner->addDecl(FD);
564 return FD;
565 }
566
567 NamedDecl *ND = D->getFriendDecl();
568 assert(ND && "friend decl must be a decl or a type!");
569
John McCallaf2094e2010-04-08 09:05:18 +0000570 // All of the Visit implementations for the various potential friend
571 // declarations have to be carefully written to work for friend
572 // objects, with the most important detail being that the target
573 // decl should almost certainly not be placed in Owner.
574 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000575 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCall02cace72009-08-28 07:59:38 +0000577 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000578 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
579 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000580 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000581 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000582 Owner->addDecl(FD);
583 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000584}
585
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
587 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Douglas Gregorac7610d2009-06-22 20:57:11 +0000589 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000590 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
John McCall60d7b3a2010-08-24 06:29:42 +0000592 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000593 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000594 if (InstantiatedAssertExpr.isInvalid())
595 return 0;
596
John McCall60d7b3a2010-08-24 06:29:42 +0000597 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000598 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000599 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000600 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000601 Message.get(),
602 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603}
604
605Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000606 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000607 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000608 /*PrevDecl=*/0, D->isScoped(),
609 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000610 if (D->isFixed()) {
611 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
612 // If we have type source information for the underlying type, it means it
613 // has been explicitly set by the user. Perform substitution on it before
614 // moving on.
615 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
616 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
617 TemplateArgs,
618 UnderlyingLoc,
619 DeclarationName()));
620
621 if (!Enum->getIntegerTypeSourceInfo())
622 Enum->setIntegerType(SemaRef.Context.IntTy);
623 }
624 else {
625 assert(!D->getIntegerType()->isDependentType()
626 && "Dependent type without type source info");
627 Enum->setIntegerType(D->getIntegerType());
628 }
629 }
630
John McCall5b629aa2010-10-22 23:36:17 +0000631 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
632
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000633 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000634 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000635 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000636 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000637 Enum->startDefinition();
638
Douglas Gregor96084f12010-03-01 19:00:07 +0000639 if (D->getDeclContext()->isFunctionOrMethod())
640 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
641
John McCalld226f652010-08-21 09:40:31 +0000642 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000643
644 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000645 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
646 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000647 EC != ECEnd; ++EC) {
648 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000649 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000650 if (Expr *UninstValue = EC->getInitExpr()) {
651 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000652 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000653 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000654
John McCallce3ff2b2009-08-25 22:02:44 +0000655 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000656 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000657
658 // Drop the initial value and continue.
659 bool isInvalid = false;
660 if (Value.isInvalid()) {
661 Value = SemaRef.Owned((Expr *)0);
662 isInvalid = true;
663 }
664
Mike Stump1eb44332009-09-09 15:08:12 +0000665 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000666 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
667 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000668 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000669
670 if (isInvalid) {
671 if (EnumConst)
672 EnumConst->setInvalidDecl();
673 Enum->setInvalidDecl();
674 }
675
676 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000677 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
678
John McCall3b85ecf2010-01-23 22:37:59 +0000679 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000680 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000681 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000682 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000683
684 if (D->getDeclContext()->isFunctionOrMethod()) {
685 // If the enumeration is within a function or method, record the enum
686 // constant as a local.
687 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
688 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000689 }
690 }
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000692 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000693 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000694 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000695 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000696 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000697 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000698
699 return Enum;
700}
701
Douglas Gregor6477b692009-03-25 15:04:13 +0000702Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
703 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
704 return 0;
705}
706
John McCalle29ba202009-08-20 01:44:21 +0000707Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000708 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
709
Douglas Gregor550d9b22009-10-31 17:21:17 +0000710 // Create a local instantiation scope for this class template, which
711 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000712 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000713 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000714 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000715 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000716 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000717
718 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000719
720 // Instantiate the qualifier. We have to do this first in case
721 // we're a friend declaration, because if we are then we need to put
722 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000723 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
724 if (QualifierLoc) {
725 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
726 TemplateArgs);
727 if (!QualifierLoc)
728 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000729 }
730
731 CXXRecordDecl *PrevDecl = 0;
732 ClassTemplateDecl *PrevClassTemplate = 0;
733
Nick Lewycky37574f52010-11-08 23:29:42 +0000734 if (!isFriend && Pattern->getPreviousDeclaration()) {
735 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
736 if (Found.first != Found.second) {
737 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
738 if (PrevClassTemplate)
739 PrevDecl = PrevClassTemplate->getTemplatedDecl();
740 }
741 }
742
John McCall93ba8572010-03-25 06:39:04 +0000743 // If this isn't a friend, then it's a member template, in which
744 // case we just want to build the instantiation in the
745 // specialization. If it is a friend, we want to build it in
746 // the appropriate context.
747 DeclContext *DC = Owner;
748 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000749 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000750 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000751 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000752 DC = SemaRef.computeDeclContext(SS);
753 if (!DC) return 0;
754 } else {
755 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
756 Pattern->getDeclContext(),
757 TemplateArgs);
758 }
759
760 // Look for a previous declaration of the template in the owning
761 // context.
762 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
763 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
764 SemaRef.LookupQualifiedName(R, DC);
765
766 if (R.isSingleResult()) {
767 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
768 if (PrevClassTemplate)
769 PrevDecl = PrevClassTemplate->getTemplatedDecl();
770 }
771
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000772 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000773 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000774 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000775 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000776 return 0;
777 }
778
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000779 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000780 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000781 bool Complain = true;
782
783 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
784 // template for struct std::tr1::__detail::_Map_base, where the
785 // template parameters of the friend declaration don't match the
786 // template parameters of the original declaration. In this one
787 // case, we don't complain about the ill-formed friend
788 // declaration.
789 if (isFriend && Pattern->getIdentifier() &&
790 Pattern->getIdentifier()->isStr("_Map_base") &&
791 DC->isNamespace() &&
792 cast<NamespaceDecl>(DC)->getIdentifier() &&
793 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
794 DeclContext *DCParent = DC->getParent();
795 if (DCParent->isNamespace() &&
796 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
797 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
798 DeclContext *DCParent2 = DCParent->getParent();
799 if (DCParent2->isNamespace() &&
800 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
801 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
802 DCParent2->getParent()->isTranslationUnit())
803 Complain = false;
804 }
805 }
806
John McCall93ba8572010-03-25 06:39:04 +0000807 TemplateParameterList *PrevParams
808 = PrevClassTemplate->getTemplateParameters();
809
810 // Make sure the parameter lists match.
811 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000812 Complain,
813 Sema::TPL_TemplateMatch)) {
814 if (Complain)
815 return 0;
816
817 AdoptedPreviousTemplateParams = true;
818 InstParams = PrevParams;
819 }
John McCall93ba8572010-03-25 06:39:04 +0000820
821 // Do some additional validation, then merge default arguments
822 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000823 if (!AdoptedPreviousTemplateParams &&
824 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000825 Sema::TPC_ClassTemplate))
826 return 0;
827 }
828 }
829
John McCalle29ba202009-08-20 01:44:21 +0000830 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000831 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000832 Pattern->getLocStart(), Pattern->getLocation(),
833 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000834 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000835
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000836 if (QualifierLoc)
837 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000838
John McCalle29ba202009-08-20 01:44:21 +0000839 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000840 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
841 D->getIdentifier(), InstParams, RecordInst,
842 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000843 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000844
John McCall93ba8572010-03-25 06:39:04 +0000845 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000846 if (PrevClassTemplate)
847 Inst->setAccess(PrevClassTemplate->getAccess());
848 else
849 Inst->setAccess(D->getAccess());
850
John McCall93ba8572010-03-25 06:39:04 +0000851 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
852 // TODO: do we want to track the instantiation progeny of this
853 // friend target decl?
854 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000855 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000856 if (!PrevClassTemplate)
857 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000858 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000859
860 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000861 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000862 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000863
Douglas Gregor259571e2009-10-30 22:42:42 +0000864 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000865 if (isFriend) {
866 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000867 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000868 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000869
John McCalle29ba202009-08-20 01:44:21 +0000870 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000871
872 if (!PrevClassTemplate) {
873 // Queue up any out-of-line partial specializations of this member
874 // class template; the client will force their instantiation once
875 // the enclosing class has been instantiated.
876 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
877 D->getPartialSpecializations(PartialSpecs);
878 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
879 if (PartialSpecs[I]->isOutOfLine())
880 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
881 }
882
John McCalle29ba202009-08-20 01:44:21 +0000883 return Inst;
884}
885
Douglas Gregord60e1052009-08-27 16:57:43 +0000886Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000887TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
888 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000889 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
890
891 // Lookup the already-instantiated declaration in the instantiation
892 // of the class template and return that.
893 DeclContext::lookup_result Found
894 = Owner->lookup(ClassTemplate->getDeclName());
895 if (Found.first == Found.second)
896 return 0;
897
898 ClassTemplateDecl *InstClassTemplate
899 = dyn_cast<ClassTemplateDecl>(*Found.first);
900 if (!InstClassTemplate)
901 return 0;
902
Douglas Gregord65587f2010-11-10 19:44:59 +0000903 if (ClassTemplatePartialSpecializationDecl *Result
904 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
905 return Result;
906
907 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000908}
909
910Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000911TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000912 // Create a local instantiation scope for this function template, which
913 // will contain the instantiations of the template parameters and then get
914 // merged with the local instantiation scope for the function template
915 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000916 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000917
Douglas Gregord60e1052009-08-27 16:57:43 +0000918 TemplateParameterList *TempParams = D->getTemplateParameters();
919 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000920 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000921 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000922
Douglas Gregora735b202009-10-13 14:39:41 +0000923 FunctionDecl *Instantiated = 0;
924 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
925 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
926 InstParams));
927 else
928 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
929 D->getTemplatedDecl(),
930 InstParams));
931
932 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000933 return 0;
934
John McCall46460a62010-01-20 21:53:11 +0000935 Instantiated->setAccess(D->getAccess());
936
Mike Stump1eb44332009-09-09 15:08:12 +0000937 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000938 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000939 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000940 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000941 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000942 assert(InstTemplate &&
943 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000944
John McCallb1a56e72010-03-26 23:10:15 +0000945 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
946
John McCalle976ffe2009-12-14 23:19:40 +0000947 // Link the instantiation back to the pattern *unless* this is a
948 // non-definition friend declaration.
949 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000950 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000951 InstTemplate->setInstantiatedFromMemberTemplate(D);
952
John McCallb1a56e72010-03-26 23:10:15 +0000953 // Make declarations visible in the appropriate context.
954 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000955 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000956
Douglas Gregord60e1052009-08-27 16:57:43 +0000957 return InstTemplate;
958}
959
Douglas Gregord475b8d2009-03-25 21:17:03 +0000960Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
961 CXXRecordDecl *PrevDecl = 0;
962 if (D->isInjectedClassName())
963 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000964 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000965 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
966 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000967 TemplateArgs);
968 if (!Prev) return 0;
969 PrevDecl = cast<CXXRecordDecl>(Prev);
970 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000971
972 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000973 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000974 D->getLocStart(), D->getLocation(),
975 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000976
977 // Substitute the nested name specifier, if any.
978 if (SubstQualifier(D, Record))
979 return 0;
980
Douglas Gregord475b8d2009-03-25 21:17:03 +0000981 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000982 // FIXME: Check against AS_none is an ugly hack to work around the issue that
983 // the tag decls introduced by friend class declarations don't have an access
984 // specifier. Remove once this area of the code gets sorted out.
985 if (D->getAccess() != AS_none)
986 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000987 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000988 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000989
John McCall02cace72009-08-28 07:59:38 +0000990 // If the original function was part of a friend declaration,
991 // inherit its namespace state.
992 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
993 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
994
Douglas Gregor9901c572010-05-21 00:31:19 +0000995 // Make sure that anonymous structs and unions are recorded.
996 if (D->isAnonymousStructOrUnion()) {
997 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000998 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000999 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1000 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001001
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001002 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001003 return Record;
1004}
1005
John McCall02cace72009-08-28 07:59:38 +00001006/// Normal class members are of more specific types and therefore
1007/// don't make it here. This function serves two purposes:
1008/// 1) instantiating function templates
1009/// 2) substituting friend declarations
1010/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001011Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001012 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001013 // Check whether there is already a function template specialization for
1014 // this declaration.
1015 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1016 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +00001017 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +00001018 std::pair<const TemplateArgument *, unsigned> Innermost
1019 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001021 FunctionDecl *SpecFunc
1022 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1023 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Douglas Gregor127102b2009-06-29 20:59:39 +00001025 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001026 if (SpecFunc)
1027 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
John McCallb0cb0222010-03-27 05:57:59 +00001030 bool isFriend;
1031 if (FunctionTemplate)
1032 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1033 else
1034 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1035
Douglas Gregor79c22782010-01-16 20:21:20 +00001036 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001037 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +00001038 !(isa<Decl>(Owner) &&
1039 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001040 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregore53060f2009-06-25 22:08:12 +00001042 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001043 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1044 TInfo = SubstFunctionType(D, Params);
1045 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001046 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001047 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001049 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1050 if (QualifierLoc) {
1051 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1052 TemplateArgs);
1053 if (!QualifierLoc)
1054 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001055 }
1056
John McCall68b6b872010-02-06 01:50:47 +00001057 // If we're instantiating a local function declaration, put the result
1058 // in the owner; otherwise we need to find the instantiated context.
1059 DeclContext *DC;
1060 if (D->getDeclContext()->isFunctionOrMethod())
1061 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001062 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001063 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001064 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001065 DC = SemaRef.computeDeclContext(SS);
1066 if (!DC) return 0;
1067 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001068 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1069 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001070 }
John McCall68b6b872010-02-06 01:50:47 +00001071
John McCall02cace72009-08-28 07:59:38 +00001072 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001073 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1074 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001075 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001076 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001077
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001078 if (QualifierLoc)
1079 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001080
John McCallb1a56e72010-03-26 23:10:15 +00001081 DeclContext *LexicalDC = Owner;
1082 if (!isFriend && D->isOutOfLine()) {
1083 assert(D->getDeclContext()->isFileContext());
1084 LexicalDC = D->getDeclContext();
1085 }
1086
1087 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregore53060f2009-06-25 22:08:12 +00001089 // Attach the parameters
1090 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001091 if (Params[P])
1092 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001093 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001094
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001095 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001096 if (TemplateParams) {
1097 // Our resulting instantiation is actually a function template, since we
1098 // are substituting only the outer template parameters. For example, given
1099 //
1100 // template<typename T>
1101 // struct X {
1102 // template<typename U> friend void f(T, U);
1103 // };
1104 //
1105 // X<int> x;
1106 //
1107 // We are instantiating the friend function template "f" within X<int>,
1108 // which means substituting int for T, but leaving "f" as a friend function
1109 // template.
1110 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001111 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001112 Function->getLocation(),
1113 Function->getDeclName(),
1114 TemplateParams, Function);
1115 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001116
1117 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001118
1119 if (isFriend && D->isThisDeclarationADefinition()) {
1120 // TODO: should we remember this connection regardless of whether
1121 // the friend declaration provided a body?
1122 FunctionTemplate->setInstantiatedFromMemberTemplate(
1123 D->getDescribedFunctionTemplate());
1124 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001125 } else if (FunctionTemplate) {
1126 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001127 std::pair<const TemplateArgument *, unsigned> Innermost
1128 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001129 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001130 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001131 Innermost.first,
1132 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001133 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001134 } else if (isFriend && D->isThisDeclarationADefinition()) {
1135 // TODO: should we remember this connection regardless of whether
1136 // the friend declaration provided a body?
1137 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001138 }
Douglas Gregora735b202009-10-13 14:39:41 +00001139
Douglas Gregore53060f2009-06-25 22:08:12 +00001140 if (InitFunctionInstantiation(Function, D))
1141 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Douglas Gregore53060f2009-06-25 22:08:12 +00001143 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001144 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001145
John McCall68263142009-11-18 22:49:29 +00001146 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1147 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1148
John McCallaf2094e2010-04-08 09:05:18 +00001149 if (DependentFunctionTemplateSpecializationInfo *Info
1150 = D->getDependentSpecializationInfo()) {
1151 assert(isFriend && "non-friend has dependent specialization info?");
1152
1153 // This needs to be set now for future sanity.
1154 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1155
1156 // Instantiate the explicit template arguments.
1157 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1158 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001159 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1160 ExplicitArgs, TemplateArgs))
1161 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001162
1163 // Map the candidate templates to their instantiations.
1164 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1165 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1166 Info->getTemplate(I),
1167 TemplateArgs);
1168 if (!Temp) return 0;
1169
1170 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1171 }
1172
1173 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1174 &ExplicitArgs,
1175 Previous))
1176 Function->setInvalidDecl();
1177
1178 isExplicitSpecialization = true;
1179
1180 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001181 // Look only into the namespace where the friend would be declared to
1182 // find a previous declaration. This is the innermost enclosing namespace,
1183 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001184 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001185
Douglas Gregora735b202009-10-13 14:39:41 +00001186 // In C++, the previous declaration we find might be a tag type
1187 // (class or enum). In this case, the new declaration will hide the
1188 // tag type. Note that this does does not apply if we're declaring a
1189 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001190 if (Previous.isSingleTagDecl())
1191 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001192 }
1193
John McCall9f54ad42009-12-10 09:41:52 +00001194 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001195 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001196
John McCall76d32642010-04-24 01:30:58 +00001197 NamedDecl *PrincipalDecl = (TemplateParams
1198 ? cast<NamedDecl>(FunctionTemplate)
1199 : Function);
1200
Douglas Gregora735b202009-10-13 14:39:41 +00001201 // If the original function was part of a friend declaration,
1202 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001203 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001204 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001205 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001206 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001207 else
Douglas Gregora735b202009-10-13 14:39:41 +00001208 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001209
1210 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1211 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001212
Gabor Greif77535df2010-08-30 22:25:56 +00001213 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001214
Douglas Gregor238058c2010-05-18 05:45:02 +00001215 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1216 D->isThisDeclarationADefinition()) {
1217 // Check for a function body.
1218 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001219 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001220 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1221 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1222 << Function->getDeclName();
1223 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1224 Function->setInvalidDecl();
1225 }
1226 // Check for redefinitions due to other instantiations of this or
1227 // a similar friend function.
1228 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1229 REnd = Function->redecls_end();
1230 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001231 if (*R == Function)
1232 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001233 switch (R->getFriendObjectKind()) {
1234 case Decl::FOK_None:
1235 if (!queuedInstantiation && R->isUsed(false)) {
1236 if (MemberSpecializationInfo *MSInfo
1237 = Function->getMemberSpecializationInfo()) {
1238 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1239 SourceLocation Loc = R->getLocation(); // FIXME
1240 MSInfo->setPointOfInstantiation(Loc);
1241 SemaRef.PendingLocalImplicitInstantiations.push_back(
1242 std::make_pair(Function, Loc));
1243 queuedInstantiation = true;
1244 }
1245 }
1246 }
1247 break;
1248 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001249 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001250 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001251 if (RPattern->isDefined(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001252 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1253 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001254 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001255 Function->setInvalidDecl();
1256 break;
1257 }
1258 }
1259 }
1260 }
Douglas Gregora735b202009-10-13 14:39:41 +00001261 }
1262
John McCall76d32642010-04-24 01:30:58 +00001263 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1264 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1265 PrincipalDecl->setNonMemberOperator();
1266
Sean Hunteb88ae52011-05-23 21:07:59 +00001267 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001268 return Function;
1269}
1270
Douglas Gregord60e1052009-08-27 16:57:43 +00001271Decl *
1272TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1273 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001274 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1275 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001276 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001277 // We are creating a function template specialization from a function
1278 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001279 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001280 std::pair<const TemplateArgument *, unsigned> Innermost
1281 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001283 FunctionDecl *SpecFunc
1284 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1285 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregor6b906862009-08-21 00:16:32 +00001287 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001288 if (SpecFunc)
1289 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001290 }
1291
John McCallb0cb0222010-03-27 05:57:59 +00001292 bool isFriend;
1293 if (FunctionTemplate)
1294 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1295 else
1296 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1297
Douglas Gregor79c22782010-01-16 20:21:20 +00001298 bool MergeWithParentScope = (TemplateParams != 0) ||
1299 !(isa<Decl>(Owner) &&
1300 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001301 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001302
John McCall4eab39f2010-10-19 02:26:41 +00001303 // Instantiate enclosing template arguments for friends.
1304 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1305 unsigned NumTempParamLists = 0;
1306 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1307 TempParamLists.set_size(NumTempParamLists);
1308 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1309 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1310 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1311 if (!InstParams)
1312 return NULL;
1313 TempParamLists[I] = InstParams;
1314 }
1315 }
1316
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001317 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001318 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1319 TInfo = SubstFunctionType(D, Params);
1320 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001321 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001322 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001323
Abramo Bagnara723df242010-12-14 22:11:44 +00001324 // \brief If the type of this function, after ignoring parentheses,
1325 // is not *directly* a function type, then we're instantiating a function
1326 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001327 //
1328 // typedef int functype(int, int);
1329 // functype func;
1330 //
1331 // In this case, we'll just go instantiate the ParmVarDecls that we
1332 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001333 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001334 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001335 llvm::SmallVector<QualType, 4> ParamTypes;
1336 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1337 D->getNumParams(), TemplateArgs, ParamTypes,
1338 &Params))
1339 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001340 }
1341
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001342 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1343 if (QualifierLoc) {
1344 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001345 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001346 if (!QualifierLoc)
1347 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001348 }
1349
1350 DeclContext *DC = Owner;
1351 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001352 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001353 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001354 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001355 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001356
1357 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1358 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001359 } else {
1360 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1361 D->getDeclContext(),
1362 TemplateArgs);
1363 }
1364 if (!DC) return 0;
1365 }
1366
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001367 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001368 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001369 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001371 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001372 DeclarationNameInfo NameInfo
1373 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001374 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001375 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001376 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001377 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001378 Constructor->isInlineSpecified(),
Sean Hunt5f802e52011-05-06 00:11:07 +00001379 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001380 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001381 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001382 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001383 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001384 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001385 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001386 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001387 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001388 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001389 Conversion->isExplicit(),
1390 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001391 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001392 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001393 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001394 D->isStatic(),
1395 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001396 D->isInlineSpecified(),
1397 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001398 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001399
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001400 if (QualifierLoc)
1401 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001402
Douglas Gregord60e1052009-08-27 16:57:43 +00001403 if (TemplateParams) {
1404 // Our resulting instantiation is actually a function template, since we
1405 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001406 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001407 // template<typename T>
1408 // struct X {
1409 // template<typename U> void f(T, U);
1410 // };
1411 //
1412 // X<int> x;
1413 //
1414 // We are instantiating the member template "f" within X<int>, which means
1415 // substituting int for T, but leaving "f" as a member function template.
1416 // Build the function template itself.
1417 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1418 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001419 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001420 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001421 if (isFriend) {
1422 FunctionTemplate->setLexicalDeclContext(Owner);
1423 FunctionTemplate->setObjectOfFriendDecl(true);
1424 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001425 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001426 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001427 } else if (FunctionTemplate) {
1428 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001429 std::pair<const TemplateArgument *, unsigned> Innermost
1430 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001431 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001432 TemplateArgumentList::CreateCopy(SemaRef.Context,
1433 Innermost.first,
1434 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001435 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001436 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001437 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001438 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001439 }
1440
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001442 // out-of-line, the instantiation will have the same lexical
1443 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001444 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001445 if (NumTempParamLists)
1446 Method->setTemplateParameterListsInfo(SemaRef.Context,
1447 NumTempParamLists,
1448 TempParamLists.data());
1449
John McCallb0cb0222010-03-27 05:57:59 +00001450 Method->setLexicalDeclContext(Owner);
1451 Method->setObjectOfFriendDecl(true);
1452 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001453 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Douglas Gregor5545e162009-03-24 00:38:23 +00001455 // Attach the parameters
1456 for (unsigned P = 0; P < Params.size(); ++P)
1457 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001458 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001459
1460 if (InitMethodInstantiation(Method, D))
1461 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001462
Abramo Bagnara25777432010-08-11 22:01:17 +00001463 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1464 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
John McCallb0cb0222010-03-27 05:57:59 +00001466 if (!FunctionTemplate || TemplateParams || isFriend) {
1467 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregordec06662009-08-21 18:42:58 +00001469 // In C++, the previous declaration we find might be a tag type
1470 // (class or enum). In this case, the new declaration will hide the
1471 // tag type. Note that this does does not apply if we're declaring a
1472 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001473 if (Previous.isSingleTagDecl())
1474 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001475 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001476
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001477 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001478 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001479
Douglas Gregor4ba31362009-12-01 17:24:26 +00001480 if (D->isPure())
1481 SemaRef.CheckPureMethod(Method, SourceRange());
1482
John McCall46460a62010-01-20 21:53:11 +00001483 Method->setAccess(D->getAccess());
1484
Anders Carlsson9eefa222011-01-20 06:52:44 +00001485 SemaRef.CheckOverrideControl(Method);
1486
John McCallb0cb0222010-03-27 05:57:59 +00001487 if (FunctionTemplate) {
1488 // If there's a function template, let our caller handle it.
1489 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1490 // Don't hide a (potentially) valid declaration with an invalid one.
1491 } else {
1492 NamedDecl *DeclToAdd = (TemplateParams
1493 ? cast<NamedDecl>(FunctionTemplate)
1494 : Method);
1495 if (isFriend)
1496 Record->makeDeclVisibleInContext(DeclToAdd);
1497 else
1498 Owner->addDecl(DeclToAdd);
1499 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001500
1501 if (D->isExplicitlyDefaulted()) {
1502 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1503 } else {
1504 assert(!D->isDefaulted() &&
1505 "should not implicitly default uninstantiated function");
1506 }
1507
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001508 return Method;
1509}
1510
Douglas Gregor615c5d42009-03-24 16:43:20 +00001511Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001512 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001513}
1514
Douglas Gregor03b2b072009-03-24 00:15:49 +00001515Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001516 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001517}
1518
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001519Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001520 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001521}
1522
Douglas Gregor6477b692009-03-25 15:04:13 +00001523ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001524 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1525 llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001526}
1527
John McCalle29ba202009-08-20 01:44:21 +00001528Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1529 TemplateTypeParmDecl *D) {
1530 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001531 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001532
John McCalle29ba202009-08-20 01:44:21 +00001533 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001534 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1535 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001536 D->getDepth() - TemplateArgs.getNumLevels(),
1537 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001538 D->wasDeclaredWithTypename(),
1539 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001540 Inst->setAccess(AS_public);
1541
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001542 if (D->hasDefaultArgument())
1543 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001544
Douglas Gregor550d9b22009-10-31 17:21:17 +00001545 // Introduce this template parameter's instantiation into the instantiation
1546 // scope.
1547 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1548
John McCalle29ba202009-08-20 01:44:21 +00001549 return Inst;
1550}
1551
Douglas Gregor33642df2009-10-23 23:25:44 +00001552Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1553 NonTypeTemplateParmDecl *D) {
1554 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001555 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1556 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1557 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1558 bool IsExpandedParameterPack = false;
1559 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001560 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001561 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001562
1563 if (D->isExpandedParameterPack()) {
1564 // The non-type template parameter pack is an already-expanded pack
1565 // expansion of types. Substitute into each of the expanded types.
1566 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1567 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1568 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1569 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1570 TemplateArgs,
1571 D->getLocation(),
1572 D->getDeclName());
1573 if (!NewDI)
1574 return 0;
1575
1576 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1577 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1578 D->getLocation());
1579 if (NewT.isNull())
1580 return 0;
1581 ExpandedParameterPackTypes.push_back(NewT);
1582 }
1583
1584 IsExpandedParameterPack = true;
1585 DI = D->getTypeSourceInfo();
1586 T = DI->getType();
1587 } else if (isa<PackExpansionTypeLoc>(TL)) {
1588 // The non-type template parameter pack's type is a pack expansion of types.
1589 // Determine whether we need to expand this parameter pack into separate
1590 // types.
1591 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1592 TypeLoc Pattern = Expansion.getPatternLoc();
1593 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1594 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1595
1596 // Determine whether the set of unexpanded parameter packs can and should
1597 // be expanded.
1598 bool Expand = true;
1599 bool RetainExpansion = false;
1600 llvm::Optional<unsigned> OrigNumExpansions
1601 = Expansion.getTypePtr()->getNumExpansions();
1602 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1603 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1604 Pattern.getSourceRange(),
1605 Unexpanded.data(),
1606 Unexpanded.size(),
1607 TemplateArgs,
1608 Expand, RetainExpansion,
1609 NumExpansions))
1610 return 0;
1611
1612 if (Expand) {
1613 for (unsigned I = 0; I != *NumExpansions; ++I) {
1614 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1615 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1616 D->getLocation(),
1617 D->getDeclName());
1618 if (!NewDI)
1619 return 0;
1620
1621 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1622 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1623 NewDI->getType(),
1624 D->getLocation());
1625 if (NewT.isNull())
1626 return 0;
1627 ExpandedParameterPackTypes.push_back(NewT);
1628 }
1629
1630 // Note that we have an expanded parameter pack. The "type" of this
1631 // expanded parameter pack is the original expansion type, but callers
1632 // will end up using the expanded parameter pack types for type-checking.
1633 IsExpandedParameterPack = true;
1634 DI = D->getTypeSourceInfo();
1635 T = DI->getType();
1636 } else {
1637 // We cannot fully expand the pack expansion now, so substitute into the
1638 // pattern and create a new pack expansion type.
1639 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1640 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1641 D->getLocation(),
1642 D->getDeclName());
1643 if (!NewPattern)
1644 return 0;
1645
1646 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1647 NumExpansions);
1648 if (!DI)
1649 return 0;
1650
1651 T = DI->getType();
1652 }
1653 } else {
1654 // Simple case: substitution into a parameter that is not a parameter pack.
1655 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1656 D->getLocation(), D->getDeclName());
1657 if (!DI)
1658 return 0;
1659
1660 // Check that this type is acceptable for a non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001661 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1662 D->getLocation());
1663 if (T.isNull()) {
1664 T = SemaRef.Context.IntTy;
1665 Invalid = true;
1666 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001667 }
1668
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001669 NonTypeTemplateParmDecl *Param;
1670 if (IsExpandedParameterPack)
1671 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001672 D->getInnerLocStart(),
1673 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001674 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001675 D->getPosition(),
1676 D->getIdentifier(), T,
1677 DI,
1678 ExpandedParameterPackTypes.data(),
1679 ExpandedParameterPackTypes.size(),
1680 ExpandedParameterPackTypesAsWritten.data());
1681 else
1682 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001683 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001684 D->getLocation(),
1685 D->getDepth() - TemplateArgs.getNumLevels(),
1686 D->getPosition(),
1687 D->getIdentifier(), T,
1688 D->isParameterPack(), DI);
1689
Douglas Gregor9a299e02011-03-04 17:52:15 +00001690 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001691 if (Invalid)
1692 Param->setInvalidDecl();
1693
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001694 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001695
1696 // Introduce this template parameter's instantiation into the instantiation
1697 // scope.
1698 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001699 return Param;
1700}
1701
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001702Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001703TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1704 TemplateTemplateParmDecl *D) {
1705 // Instantiate the template parameter list of the template template parameter.
1706 TemplateParameterList *TempParams = D->getTemplateParameters();
1707 TemplateParameterList *InstParams;
1708 {
1709 // Perform the actual substitution of template parameters within a new,
1710 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001711 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001712 InstParams = SubstTemplateParams(TempParams);
1713 if (!InstParams)
1714 return NULL;
1715 }
1716
1717 // Build the template template parameter.
1718 TemplateTemplateParmDecl *Param
1719 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001720 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001721 D->getPosition(), D->isParameterPack(),
1722 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001723 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001724 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001725
Douglas Gregor9106ef72009-11-11 16:58:32 +00001726 // Introduce this template parameter's instantiation into the instantiation
1727 // scope.
1728 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1729
1730 return Param;
1731}
1732
Douglas Gregor48c32a72009-11-17 06:07:40 +00001733Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001734 // Using directives are never dependent (and never contain any types or
1735 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001736
1737 UsingDirectiveDecl *Inst
1738 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1739 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001740 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001741 D->getIdentLocation(),
1742 D->getNominatedNamespace(),
1743 D->getCommonAncestor());
1744 Owner->addDecl(Inst);
1745 return Inst;
1746}
1747
John McCalled976492009-12-04 22:46:56 +00001748Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001749
1750 // The nested name specifier may be dependent, for example
1751 // template <typename T> struct t {
1752 // struct s1 { T f1(); };
1753 // struct s2 : s1 { using s1::f1; };
1754 // };
1755 // template struct t<int>;
1756 // Here, in using s1::f1, s1 refers to t<T>::s1;
1757 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001758 NestedNameSpecifierLoc QualifierLoc
1759 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1760 TemplateArgs);
1761 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001762 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001763
1764 // The name info is non-dependent, so no transformation
1765 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001766 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001767
John McCall9f54ad42009-12-10 09:41:52 +00001768 // We only need to do redeclaration lookups if we're in a class
1769 // scope (in fact, it's not really even possible in non-class
1770 // scopes).
1771 bool CheckRedeclaration = Owner->isRecord();
1772
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001773 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1774 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001775
John McCalled976492009-12-04 22:46:56 +00001776 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001777 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001778 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001779 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001780 D->isTypeName());
1781
Douglas Gregor5149f372011-02-25 15:54:31 +00001782 CXXScopeSpec SS;
1783 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001784 if (CheckRedeclaration) {
1785 Prev.setHideTags(false);
1786 SemaRef.LookupQualifiedName(Prev, Owner);
1787
1788 // Check for invalid redeclarations.
1789 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1790 D->isTypeName(), SS,
1791 D->getLocation(), Prev))
1792 NewUD->setInvalidDecl();
1793
1794 }
1795
1796 if (!NewUD->isInvalidDecl() &&
1797 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001798 D->getLocation()))
1799 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001800
John McCalled976492009-12-04 22:46:56 +00001801 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1802 NewUD->setAccess(D->getAccess());
1803 Owner->addDecl(NewUD);
1804
John McCall9f54ad42009-12-10 09:41:52 +00001805 // Don't process the shadow decls for an invalid decl.
1806 if (NewUD->isInvalidDecl())
1807 return NewUD;
1808
John McCall323c3102009-12-22 22:26:37 +00001809 bool isFunctionScope = Owner->isFunctionOrMethod();
1810
John McCall9f54ad42009-12-10 09:41:52 +00001811 // Process the shadow decls.
1812 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1813 I != E; ++I) {
1814 UsingShadowDecl *Shadow = *I;
1815 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001816 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1817 Shadow->getLocation(),
1818 Shadow->getTargetDecl(),
1819 TemplateArgs));
1820 if (!InstTarget)
1821 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001822
1823 if (CheckRedeclaration &&
1824 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1825 continue;
1826
1827 UsingShadowDecl *InstShadow
1828 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1829 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001830
1831 if (isFunctionScope)
1832 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001833 }
John McCalled976492009-12-04 22:46:56 +00001834
1835 return NewUD;
1836}
1837
1838Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001839 // Ignore these; we handle them in bulk when processing the UsingDecl.
1840 return 0;
John McCalled976492009-12-04 22:46:56 +00001841}
1842
John McCall7ba107a2009-11-18 02:36:19 +00001843Decl * TemplateDeclInstantiator
1844 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001845 NestedNameSpecifierLoc QualifierLoc
1846 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1847 TemplateArgs);
1848 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001849 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001851 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001852 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001854 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1855 // Hence, no tranformation is required for it.
1856 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001857 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001858 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001859 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001860 /*instantiation*/ true,
1861 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001862 if (UD)
John McCalled976492009-12-04 22:46:56 +00001863 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1864
John McCall7ba107a2009-11-18 02:36:19 +00001865 return UD;
1866}
1867
1868Decl * TemplateDeclInstantiator
1869 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001870 NestedNameSpecifierLoc QualifierLoc
1871 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1872 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001873 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001874
John McCall7ba107a2009-11-18 02:36:19 +00001875 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001876 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001877
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001878 DeclarationNameInfo NameInfo
1879 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1880
John McCall7ba107a2009-11-18 02:36:19 +00001881 NamedDecl *UD =
1882 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001883 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001884 /*instantiation*/ true,
1885 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001886 if (UD)
John McCalled976492009-12-04 22:46:56 +00001887 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1888
Anders Carlsson0d8df782009-08-29 19:37:28 +00001889 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001890}
1891
John McCallce3ff2b2009-08-25 22:02:44 +00001892Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001893 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001894 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001895 if (D->isInvalidDecl())
1896 return 0;
1897
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001898 return Instantiator.Visit(D);
1899}
1900
John McCalle29ba202009-08-20 01:44:21 +00001901/// \brief Instantiates a nested template parameter list in the current
1902/// instantiation context.
1903///
1904/// \param L The parameter list to instantiate
1905///
1906/// \returns NULL if there was an error
1907TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001908TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001909 // Get errors for all the parameters before bailing out.
1910 bool Invalid = false;
1911
1912 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001913 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001914 ParamVector Params;
1915 Params.reserve(N);
1916 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1917 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001918 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001919 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001920 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001921 }
1922
1923 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001924 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001925 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001926
1927 TemplateParameterList *InstL
1928 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1929 L->getLAngleLoc(), &Params.front(), N,
1930 L->getRAngleLoc());
1931 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001932}
John McCalle29ba202009-08-20 01:44:21 +00001933
Douglas Gregored9c0f92009-10-29 00:04:11 +00001934/// \brief Instantiate the declaration of a class template partial
1935/// specialization.
1936///
1937/// \param ClassTemplate the (instantiated) class template that is partially
1938// specialized by the instantiation of \p PartialSpec.
1939///
1940/// \param PartialSpec the (uninstantiated) class template partial
1941/// specialization that we are instantiating.
1942///
Douglas Gregord65587f2010-11-10 19:44:59 +00001943/// \returns The instantiated partial specialization, if successful; otherwise,
1944/// NULL to indicate an error.
1945ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001946TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1947 ClassTemplateDecl *ClassTemplate,
1948 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001949 // Create a local instantiation scope for this class template partial
1950 // specialization, which will contain the instantiations of the template
1951 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001952 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001953
Douglas Gregored9c0f92009-10-29 00:04:11 +00001954 // Substitute into the template parameters of the class template partial
1955 // specialization.
1956 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1957 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1958 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001959 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001960
1961 // Substitute into the template arguments of the class template partial
1962 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001963 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001964 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1965 PartialSpec->getNumTemplateArgsAsWritten(),
1966 InstTemplateArgs, TemplateArgs))
1967 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001968
Douglas Gregored9c0f92009-10-29 00:04:11 +00001969 // Check that the template argument list is well-formed for this
1970 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001971 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001972 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1973 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001974 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001975 false,
1976 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001977 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001978
1979 // Figure out where to insert this class template partial specialization
1980 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001981 void *InsertPos = 0;
1982 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001983 = ClassTemplate->findPartialSpecialization(Converted.data(),
1984 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001985
1986 // Build the canonical type that describes the converted template
1987 // arguments of the class template partial specialization.
1988 QualType CanonType
1989 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001990 Converted.data(),
1991 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001992
1993 // Build the fully-sugared type for this class template
1994 // specialization as the user wrote in the specialization
1995 // itself. This means that we'll pretty-print the type retrieved
1996 // from the specialization's declaration the way that the user
1997 // actually wrote the specialization, rather than formatting the
1998 // name based on the "canonical" representation used to store the
1999 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002000 TypeSourceInfo *WrittenTy
2001 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2002 TemplateName(ClassTemplate),
2003 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002004 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002005 CanonType);
2006
2007 if (PrevDecl) {
2008 // We've already seen a partial specialization with the same template
2009 // parameters and template arguments. This can happen, for example, when
2010 // substituting the outer template arguments ends up causing two
2011 // class template partial specializations of a member class template
2012 // to have identical forms, e.g.,
2013 //
2014 // template<typename T, typename U>
2015 // struct Outer {
2016 // template<typename X, typename Y> struct Inner;
2017 // template<typename Y> struct Inner<T, Y>;
2018 // template<typename Y> struct Inner<U, Y>;
2019 // };
2020 //
2021 // Outer<int, int> outer; // error: the partial specializations of Inner
2022 // // have the same signature.
2023 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002024 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002025 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2026 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002027 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002028 }
2029
2030
2031 // Create the class template partial specialization declaration.
2032 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00002033 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2034 PartialSpec->getTagKind(),
2035 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002036 PartialSpec->getLocStart(),
2037 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002038 InstParams,
2039 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002040 Converted.data(),
2041 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002042 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002043 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002044 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002045 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002046 // Substitute the nested name specifier, if any.
2047 if (SubstQualifier(PartialSpec, InstPartialSpec))
2048 return 0;
2049
Douglas Gregored9c0f92009-10-29 00:04:11 +00002050 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002051 InstPartialSpec->setTypeAsWritten(WrittenTy);
2052
Douglas Gregored9c0f92009-10-29 00:04:11 +00002053 // Add this partial specialization to the set of class template partial
2054 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002055 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00002056 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002057}
2058
John McCall21ef0fa2010-03-11 09:03:00 +00002059TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002060TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002061 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002062 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2063 assert(OldTInfo && "substituting function without type source info");
2064 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002065 TypeSourceInfo *NewTInfo
2066 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2067 D->getTypeSpecStartLoc(),
2068 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002069 if (!NewTInfo)
2070 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002071
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002072 if (NewTInfo != OldTInfo) {
2073 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002074 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002075 if (FunctionProtoTypeLoc *OldProtoLoc
2076 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002077 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002078 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2079 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002080 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2081 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2082 OldIdx != NumOldParams; ++OldIdx) {
2083 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2084 if (!OldParam->isParameterPack() ||
2085 (NewIdx < NumNewParams &&
2086 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2087 // Simple case: normal parameter, or a parameter pack that's
2088 // instantiated to a (still-dependent) parameter pack.
2089 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2090 Params.push_back(NewParam);
2091 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2092 NewParam);
2093 continue;
2094 }
2095
2096 // Parameter pack: make the instantiation an argument pack.
2097 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2098 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002099 unsigned NumArgumentsInExpansion
2100 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2101 TemplateArgs);
2102 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002103 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2104 Params.push_back(NewParam);
2105 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2106 NewParam);
2107 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002108 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002109 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002110 } else {
2111 // The function type itself was not dependent and therefore no
2112 // substitution occurred. However, we still need to instantiate
2113 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002114 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002115 if (FunctionProtoTypeLoc *OldProtoLoc
2116 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2117 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2118 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2119 if (!Parm)
2120 return 0;
2121 Params.push_back(Parm);
2122 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002123 }
2124 }
John McCall21ef0fa2010-03-11 09:03:00 +00002125 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002126}
2127
Mike Stump1eb44332009-09-09 15:08:12 +00002128/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002129/// declaration (New) from the corresponding fields of its template (Tmpl).
2130///
2131/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002132bool
2133TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002134 FunctionDecl *Tmpl) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002135 if (Tmpl->isDeletedAsWritten())
2136 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregorcca9e962009-07-01 22:01:06 +00002138 // If we are performing substituting explicitly-specified template arguments
2139 // or deduced template arguments into a function template and we reach this
2140 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002141 // to keeping the new function template specialization. We therefore
2142 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002143 // into a template instantiation for this specific function template
2144 // specialization, which is not a SFINAE context, so that we diagnose any
2145 // further errors in the declaration itself.
2146 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2147 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2148 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2149 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002150 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002151 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002152 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002153 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002154 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002155 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2156 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002157 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002158 }
2159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002161 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2162 assert(Proto && "Function template without prototype?");
2163
Sebastian Redl60618fa2011-03-12 11:50:43 +00002164 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002165 // The function has an exception specification or a "noreturn"
2166 // attribute. Substitute into each of the exception types.
2167 llvm::SmallVector<QualType, 4> Exceptions;
2168 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2169 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002170 if (const PackExpansionType *PackExpansion
2171 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2172 // We have a pack expansion. Instantiate it.
2173 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2174 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2175 Unexpanded);
2176 assert(!Unexpanded.empty() &&
2177 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002178
Douglas Gregorb99268b2010-12-21 00:52:54 +00002179 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002180 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002181 llvm::Optional<unsigned> NumExpansions
2182 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002183 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2184 SourceRange(),
2185 Unexpanded.data(),
2186 Unexpanded.size(),
2187 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002188 Expand,
2189 RetainExpansion,
2190 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002191 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002192
Douglas Gregorb99268b2010-12-21 00:52:54 +00002193 if (!Expand) {
2194 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002195 // just substitute into the pattern and create a new pack expansion
2196 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002197 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2198 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2199 TemplateArgs,
2200 New->getLocation(), New->getDeclName());
2201 if (T.isNull())
2202 break;
2203
Douglas Gregorcded4f62011-01-14 17:04:44 +00002204 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002205 Exceptions.push_back(T);
2206 continue;
2207 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002208
Douglas Gregorb99268b2010-12-21 00:52:54 +00002209 // Substitute into the pack expansion pattern for each template
2210 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002211 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002212 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2213
2214 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2215 TemplateArgs,
2216 New->getLocation(), New->getDeclName());
2217 if (T.isNull()) {
2218 Invalid = true;
2219 break;
2220 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002221
Douglas Gregorb99268b2010-12-21 00:52:54 +00002222 Exceptions.push_back(T);
2223 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002224
Douglas Gregorb99268b2010-12-21 00:52:54 +00002225 if (Invalid)
2226 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002227
Douglas Gregorb99268b2010-12-21 00:52:54 +00002228 continue;
2229 }
2230
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002231 QualType T
2232 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2233 New->getLocation(), New->getDeclName());
2234 if (T.isNull() ||
2235 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2236 continue;
2237
2238 Exceptions.push_back(T);
2239 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002240 Expr *NoexceptExpr = 0;
2241 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2242 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2243 if (E.isUsable())
2244 NoexceptExpr = E.take();
2245 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002246
2247 // Rebuild the function type
2248
John McCalle23cf432010-12-14 08:05:40 +00002249 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002250 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002251 EPI.NumExceptions = Exceptions.size();
2252 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002253 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002254 EPI.ExtInfo = Proto->getExtInfo();
2255
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002256 const FunctionProtoType *NewProto
2257 = New->getType()->getAs<FunctionProtoType>();
2258 assert(NewProto && "Template instantiation without function prototype?");
2259 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2260 NewProto->arg_type_begin(),
2261 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002262 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002263 }
2264
John McCall1d8d1cc2010-08-01 02:01:53 +00002265 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002266
Douglas Gregore53060f2009-06-25 22:08:12 +00002267 return false;
2268}
2269
Douglas Gregor5545e162009-03-24 00:38:23 +00002270/// \brief Initializes common fields of an instantiated method
2271/// declaration (New) from the corresponding fields of its template
2272/// (Tmpl).
2273///
2274/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002275bool
2276TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002277 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002278 if (InitFunctionInstantiation(New, Tmpl))
2279 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor5545e162009-03-24 00:38:23 +00002281 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002282 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002283 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002284
2285 // FIXME: attributes
2286 // FIXME: New needs a pointer to Tmpl
2287 return false;
2288}
Douglas Gregora58861f2009-05-13 20:28:22 +00002289
2290/// \brief Instantiate the definition of the given function from its
2291/// template.
2292///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002293/// \param PointOfInstantiation the point at which the instantiation was
2294/// required. Note that this is not precisely a "point of instantiation"
2295/// for the function, but it's close.
2296///
Douglas Gregora58861f2009-05-13 20:28:22 +00002297/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002298/// function template specialization or member function of a class template
2299/// specialization.
2300///
2301/// \param Recursive if true, recursively instantiates any functions that
2302/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002303///
2304/// \param DefinitionRequired if true, then we are performing an explicit
2305/// instantiation where the body of the function is required. Complain if
2306/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002307void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002308 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002309 bool Recursive,
2310 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002311 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002312 return;
2313
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002314 // Never instantiate an explicit specialization.
2315 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2316 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002317
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002318 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002319 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002320 Stmt *Pattern = 0;
2321 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002322 Pattern = PatternDecl->getBody(PatternDecl);
Sean Huntcd10dec2011-05-23 23:14:04 +00002323 if (!Pattern)
2324 // Try to find a defaulted definition
2325 PatternDecl->isDefined(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002326
Francois Pichet8387e2a2011-04-22 22:18:13 +00002327 // Postpone late parsed template instantiations.
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002328 if (PatternDecl && PatternDecl->isLateTemplateParsed() &&
2329 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002330 PendingInstantiations.push_back(
2331 std::make_pair(Function, PointOfInstantiation));
2332 return;
2333 }
2334
2335 // Call the LateTemplateParser callback if there a need to late parse
2336 // a templated function definition.
2337 if (!Pattern && PatternDecl && PatternDecl->isLateTemplateParsed() &&
2338 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002339 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002340 Pattern = PatternDecl->getBody(PatternDecl);
2341 }
2342
Sean Huntcd10dec2011-05-23 23:14:04 +00002343 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002344 if (DefinitionRequired) {
2345 if (Function->getPrimaryTemplate())
2346 Diag(PointOfInstantiation,
2347 diag::err_explicit_instantiation_undefined_func_template)
2348 << Function->getPrimaryTemplate();
2349 else
2350 Diag(PointOfInstantiation,
2351 diag::err_explicit_instantiation_undefined_member)
2352 << 1 << Function->getDeclName() << Function->getDeclContext();
2353
2354 if (PatternDecl)
2355 Diag(PatternDecl->getLocation(),
2356 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002357 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002358 } else if (Function->getTemplateSpecializationKind()
2359 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002360 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002361 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002362 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002363
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002364 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002365 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002366
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002367 // C++0x [temp.explicit]p9:
2368 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002369 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002370 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002371 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002372 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002373 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002374 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002376 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2377 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002378 return;
2379
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002380 // If we're performing recursive template instantiation, create our own
2381 // queue of pending implicit instantiations that we will instantiate later,
2382 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002383 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002384 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002385 if (Recursive) {
2386 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002387 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002388 }
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor9679caf2010-05-12 17:27:19 +00002390 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002391 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002392 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002393
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002394 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002395 // recorded, unless we're actually a member function within a local
2396 // class, in which case we need to merge our results with the parent
2397 // scope (of the enclosing function).
2398 bool MergeWithParentScope = false;
2399 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2400 MergeWithParentScope = Rec->isLocalClass();
2401
2402 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002404 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002405 // instantiation scope, and set the parameter names to those used
2406 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002407 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002408 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2409 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002410 if (!PatternParam->isParameterPack()) {
2411 // Simple case: not a parameter pack.
2412 assert(FParamIdx < Function->getNumParams());
2413 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2414 FunctionParam->setDeclName(PatternParam->getDeclName());
2415 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2416 ++FParamIdx;
2417 continue;
2418 }
2419
2420 // Expand the parameter pack.
2421 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2422 for (unsigned NumFParams = Function->getNumParams();
2423 FParamIdx < NumFParams;
2424 ++FParamIdx) {
2425 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2426 FunctionParam->setDeclName(PatternParam->getDeclName());
2427 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2428 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002429 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002430
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002431 // Enter the scope of this instantiation. We don't use
2432 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002433 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002434
Mike Stump1eb44332009-09-09 15:08:12 +00002435 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002436 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002437
Sean Huntcd10dec2011-05-23 23:14:04 +00002438 if (PatternDecl->isDefaulted()) {
2439 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2440
2441 SetDeclDefaulted(Function, PatternDecl->getLocation());
2442
2443 return;
2444 } else {
2445 // If this is a constructor, instantiate the member initializers.
2446 if (const CXXConstructorDecl *Ctor =
2447 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2448 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2449 TemplateArgs);
2450 }
2451
2452 // Instantiate the function body.
2453 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2454
2455 if (Body.isInvalid())
2456 Function->setInvalidDecl();
2457
2458 ActOnFinishFunctionBody(Function, Body.get(),
2459 /*IsInstantiation=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002460 }
2461
John McCall0c01d182010-03-24 05:22:00 +00002462 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2463
John McCalleee1d542011-02-14 07:13:47 +00002464 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002465
2466 DeclGroupRef DG(Function);
2467 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Douglas Gregor60406be2010-01-16 22:29:39 +00002469 // This class may have local implicit instantiations that need to be
2470 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002471 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002472 Scope.Exit();
2473
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002474 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002475 // Define any pending vtables.
2476 DefineUsedVTables();
2477
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002478 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002479 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002480 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002482 // Restore the set of pending vtables.
2483 VTableUses.swap(SavedVTableUses);
2484
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002485 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002486 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002487 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002488}
2489
2490/// \brief Instantiate the definition of the given variable from its
2491/// template.
2492///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002493/// \param PointOfInstantiation the point at which the instantiation was
2494/// required. Note that this is not precisely a "point of instantiation"
2495/// for the function, but it's close.
2496///
2497/// \param Var the already-instantiated declaration of a static member
2498/// variable of a class template specialization.
2499///
2500/// \param Recursive if true, recursively instantiates any functions that
2501/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002502///
2503/// \param DefinitionRequired if true, then we are performing an explicit
2504/// instantiation where an out-of-line definition of the member variable
2505/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002506void Sema::InstantiateStaticDataMemberDefinition(
2507 SourceLocation PointOfInstantiation,
2508 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002509 bool Recursive,
2510 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002511 if (Var->isInvalidDecl())
2512 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Douglas Gregor7caa6822009-07-24 20:34:43 +00002514 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002515 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002516 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002517 assert(Def->isStaticDataMember() && "Not a static data member?");
2518 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Douglas Gregor0d035142009-10-27 18:42:08 +00002520 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002521 // We did not find an out-of-line definition of this static data member,
2522 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002523 // instantiate this definition (or provide a specialization for it) in
2524 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002525 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002526 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002527 Diag(PointOfInstantiation,
2528 diag::err_explicit_instantiation_undefined_member)
2529 << 2 << Var->getDeclName() << Var->getDeclContext();
2530 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002531 } else if (Var->getTemplateSpecializationKind()
2532 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002533 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002534 std::make_pair(Var, PointOfInstantiation));
2535 }
2536
Douglas Gregor7caa6822009-07-24 20:34:43 +00002537 return;
2538 }
2539
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002540 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002541 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002542 return;
2543
2544 // C++0x [temp.explicit]p9:
2545 // Except for inline functions, other explicit instantiation declarations
2546 // have the effect of suppressing the implicit instantiation of the entity
2547 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002548 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002549 == TSK_ExplicitInstantiationDeclaration)
2550 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Douglas Gregor7caa6822009-07-24 20:34:43 +00002552 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2553 if (Inst)
2554 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregor7caa6822009-07-24 20:34:43 +00002556 // If we're performing recursive template instantiation, create our own
2557 // queue of pending implicit instantiations that we will instantiate later,
2558 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002559 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002560 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002561 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregor7caa6822009-07-24 20:34:43 +00002563 // Enter the scope of this instantiation. We don't use
2564 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002565 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002567 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002568 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002569 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002570
2571 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002572
2573 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002574 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2575 assert(MSInfo && "Missing member specialization information?");
2576 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2577 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002578 DeclGroupRef DG(Var);
2579 Consumer.HandleTopLevelDecl(DG);
2580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregor7caa6822009-07-24 20:34:43 +00002582 if (Recursive) {
2583 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002584 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002585 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregor7caa6822009-07-24 20:34:43 +00002587 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002588 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002589 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002590}
Douglas Gregor815215d2009-05-27 05:35:12 +00002591
Anders Carlsson09025312009-08-29 05:16:22 +00002592void
2593Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2594 const CXXConstructorDecl *Tmpl,
2595 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Anders Carlsson09025312009-08-29 05:16:22 +00002597 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002598 bool AnyErrors = false;
2599
Anders Carlsson09025312009-08-29 05:16:22 +00002600 // Instantiate all the initializers.
2601 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002602 InitsEnd = Tmpl->init_end();
2603 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002604 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002605
Chandler Carruth030ef472010-09-03 21:54:20 +00002606 // Only instantiate written initializers, let Sema re-construct implicit
2607 // ones.
2608 if (!Init->isWritten())
2609 continue;
2610
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002611 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002612 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002614 SourceLocation EllipsisLoc;
2615
2616 if (Init->isPackExpansion()) {
2617 // This is a pack expansion. We should expand it now.
2618 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2619 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2620 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2621 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002622 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002623 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002624 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2625 BaseTL.getSourceRange(),
2626 Unexpanded.data(),
2627 Unexpanded.size(),
2628 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002629 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002630 NumExpansions)) {
2631 AnyErrors = true;
2632 New->setInvalidDecl();
2633 continue;
2634 }
2635 assert(ShouldExpand && "Partial instantiation of base initializer?");
2636
2637 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002638 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002639 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2640
2641 // Instantiate the initializer.
2642 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2643 LParenLoc, NewArgs, RParenLoc)) {
2644 AnyErrors = true;
2645 break;
2646 }
2647
2648 // Instantiate the base type.
2649 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2650 TemplateArgs,
2651 Init->getSourceLocation(),
2652 New->getDeclName());
2653 if (!BaseTInfo) {
2654 AnyErrors = true;
2655 break;
2656 }
2657
2658 // Build the initializer.
2659 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2660 BaseTInfo,
2661 (Expr **)NewArgs.data(),
2662 NewArgs.size(),
2663 Init->getLParenLoc(),
2664 Init->getRParenLoc(),
2665 New->getParent(),
2666 SourceLocation());
2667 if (NewInit.isInvalid()) {
2668 AnyErrors = true;
2669 break;
2670 }
2671
2672 NewInits.push_back(NewInit.get());
2673 NewArgs.clear();
2674 }
2675
2676 continue;
2677 }
2678
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002679 // Instantiate the initializer.
2680 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002681 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002682 AnyErrors = true;
2683 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002684 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002685
Anders Carlsson09025312009-08-29 05:16:22 +00002686 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002687 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002688 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002689 TemplateArgs,
2690 Init->getSourceLocation(),
2691 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002692 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002693 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002694 New->setInvalidDecl();
2695 continue;
2696 }
2697
John McCalla93c9342009-12-07 02:54:59 +00002698 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002699 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002700 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002701 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002702 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002703 New->getParent(),
2704 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002705 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002706 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002707 Init->getMemberLocation(),
2708 Init->getMember(),
2709 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002710 if (!Member) {
2711 AnyErrors = true;
2712 New->setInvalidDecl();
2713 continue;
2714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
2716 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002717 NewArgs.size(),
2718 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002719 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002720 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002721 } else if (Init->isIndirectMemberInitializer()) {
2722 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002723 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002724 Init->getMemberLocation(),
2725 Init->getIndirectMember(), TemplateArgs));
2726
Douglas Gregorb7107222011-03-04 19:46:35 +00002727 if (!IndirectMember) {
2728 AnyErrors = true;
2729 New->setInvalidDecl();
2730 continue;
2731 }
2732
Francois Pichet00eb3f92010-12-04 09:14:42 +00002733 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2734 NewArgs.size(),
2735 Init->getSourceLocation(),
2736 Init->getLParenLoc(),
2737 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002738 }
2739
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002740 if (NewInit.isInvalid()) {
2741 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002742 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002743 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002744 // FIXME: It would be nice if ASTOwningVector had a release function.
2745 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Anders Carlsson09025312009-08-29 05:16:22 +00002747 NewInits.push_back((MemInitTy *)NewInit.get());
2748 }
2749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Anders Carlsson09025312009-08-29 05:16:22 +00002751 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002752 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002753 /*FIXME: ColonLoc */
2754 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755 NewInits.data(), NewInits.size(),
2756 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002757}
2758
John McCall52a575a2009-08-29 08:11:13 +00002759// TODO: this could be templated if the various decl types used the
2760// same method name.
2761static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2762 ClassTemplateDecl *Instance) {
2763 Pattern = Pattern->getCanonicalDecl();
2764
2765 do {
2766 Instance = Instance->getCanonicalDecl();
2767 if (Pattern == Instance) return true;
2768 Instance = Instance->getInstantiatedFromMemberTemplate();
2769 } while (Instance);
2770
2771 return false;
2772}
2773
Douglas Gregor0d696532009-09-28 06:34:35 +00002774static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2775 FunctionTemplateDecl *Instance) {
2776 Pattern = Pattern->getCanonicalDecl();
2777
2778 do {
2779 Instance = Instance->getCanonicalDecl();
2780 if (Pattern == Instance) return true;
2781 Instance = Instance->getInstantiatedFromMemberTemplate();
2782 } while (Instance);
2783
2784 return false;
2785}
2786
Douglas Gregored9c0f92009-10-29 00:04:11 +00002787static bool
2788isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2789 ClassTemplatePartialSpecializationDecl *Instance) {
2790 Pattern
2791 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2792 do {
2793 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2794 Instance->getCanonicalDecl());
2795 if (Pattern == Instance)
2796 return true;
2797 Instance = Instance->getInstantiatedFromMember();
2798 } while (Instance);
2799
2800 return false;
2801}
2802
John McCall52a575a2009-08-29 08:11:13 +00002803static bool isInstantiationOf(CXXRecordDecl *Pattern,
2804 CXXRecordDecl *Instance) {
2805 Pattern = Pattern->getCanonicalDecl();
2806
2807 do {
2808 Instance = Instance->getCanonicalDecl();
2809 if (Pattern == Instance) return true;
2810 Instance = Instance->getInstantiatedFromMemberClass();
2811 } while (Instance);
2812
2813 return false;
2814}
2815
2816static bool isInstantiationOf(FunctionDecl *Pattern,
2817 FunctionDecl *Instance) {
2818 Pattern = Pattern->getCanonicalDecl();
2819
2820 do {
2821 Instance = Instance->getCanonicalDecl();
2822 if (Pattern == Instance) return true;
2823 Instance = Instance->getInstantiatedFromMemberFunction();
2824 } while (Instance);
2825
2826 return false;
2827}
2828
2829static bool isInstantiationOf(EnumDecl *Pattern,
2830 EnumDecl *Instance) {
2831 Pattern = Pattern->getCanonicalDecl();
2832
2833 do {
2834 Instance = Instance->getCanonicalDecl();
2835 if (Pattern == Instance) return true;
2836 Instance = Instance->getInstantiatedFromMemberEnum();
2837 } while (Instance);
2838
2839 return false;
2840}
2841
John McCalled976492009-12-04 22:46:56 +00002842static bool isInstantiationOf(UsingShadowDecl *Pattern,
2843 UsingShadowDecl *Instance,
2844 ASTContext &C) {
2845 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2846}
2847
2848static bool isInstantiationOf(UsingDecl *Pattern,
2849 UsingDecl *Instance,
2850 ASTContext &C) {
2851 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2852}
2853
John McCall7ba107a2009-11-18 02:36:19 +00002854static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2855 UsingDecl *Instance,
2856 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002857 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002858}
2859
2860static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002861 UsingDecl *Instance,
2862 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002863 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002864}
2865
John McCall52a575a2009-08-29 08:11:13 +00002866static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2867 VarDecl *Instance) {
2868 assert(Instance->isStaticDataMember());
2869
2870 Pattern = Pattern->getCanonicalDecl();
2871
2872 do {
2873 Instance = Instance->getCanonicalDecl();
2874 if (Pattern == Instance) return true;
2875 Instance = Instance->getInstantiatedFromStaticDataMember();
2876 } while (Instance);
2877
2878 return false;
2879}
2880
John McCalled976492009-12-04 22:46:56 +00002881// Other is the prospective instantiation
2882// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002883static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002884 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002885 if (UnresolvedUsingTypenameDecl *UUD
2886 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2887 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2888 return isInstantiationOf(UUD, UD, Ctx);
2889 }
2890 }
2891
2892 if (UnresolvedUsingValueDecl *UUD
2893 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002894 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2895 return isInstantiationOf(UUD, UD, Ctx);
2896 }
2897 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002898
Anders Carlsson0d8df782009-08-29 19:37:28 +00002899 return false;
2900 }
Mike Stump1eb44332009-09-09 15:08:12 +00002901
John McCall52a575a2009-08-29 08:11:13 +00002902 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2903 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002904
John McCall52a575a2009-08-29 08:11:13 +00002905 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2906 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002907
John McCall52a575a2009-08-29 08:11:13 +00002908 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2909 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002910
Douglas Gregor7caa6822009-07-24 20:34:43 +00002911 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002912 if (Var->isStaticDataMember())
2913 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2914
2915 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2916 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002917
Douglas Gregor0d696532009-09-28 06:34:35 +00002918 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2919 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2920
Douglas Gregored9c0f92009-10-29 00:04:11 +00002921 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2922 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2923 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2924 PartialSpec);
2925
Anders Carlssond8b285f2009-09-01 04:26:58 +00002926 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2927 if (!Field->getDeclName()) {
2928 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002929 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002930 cast<FieldDecl>(D);
2931 }
2932 }
Mike Stump1eb44332009-09-09 15:08:12 +00002933
John McCalled976492009-12-04 22:46:56 +00002934 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2935 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2936
2937 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2938 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2939
Douglas Gregor815215d2009-05-27 05:35:12 +00002940 return D->getDeclName() && isa<NamedDecl>(Other) &&
2941 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2942}
2943
2944template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002945static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002946 NamedDecl *D,
2947 ForwardIterator first,
2948 ForwardIterator last) {
2949 for (; first != last; ++first)
2950 if (isInstantiationOf(Ctx, D, *first))
2951 return cast<NamedDecl>(*first);
2952
2953 return 0;
2954}
2955
John McCall02cace72009-08-28 07:59:38 +00002956/// \brief Finds the instantiation of the given declaration context
2957/// within the current instantiation.
2958///
2959/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002960DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002961 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002962 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002963 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002964 return cast_or_null<DeclContext>(ID);
2965 } else return DC;
2966}
2967
Douglas Gregored961e72009-05-27 17:54:46 +00002968/// \brief Find the instantiation of the given declaration within the
2969/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002970///
2971/// This routine is intended to be used when \p D is a declaration
2972/// referenced from within a template, that needs to mapped into the
2973/// corresponding declaration within an instantiation. For example,
2974/// given:
2975///
2976/// \code
2977/// template<typename T>
2978/// struct X {
2979/// enum Kind {
2980/// KnownValue = sizeof(T)
2981/// };
2982///
2983/// bool getKind() const { return KnownValue; }
2984/// };
2985///
2986/// template struct X<int>;
2987/// \endcode
2988///
2989/// In the instantiation of X<int>::getKind(), we need to map the
2990/// EnumConstantDecl for KnownValue (which refers to
2991/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002992/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2993/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002994NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002995 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002996 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002997 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002998 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002999 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003000 // D is a local of some kind. Look into the map of local
3001 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003002 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3003 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3004 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00003005
Chris Lattner57ad3782011-02-17 20:34:02 +00003006 if (Found) {
3007 if (Decl *FD = Found->dyn_cast<Decl *>())
3008 return cast<NamedDecl>(FD);
3009
3010 unsigned PackIdx = ArgumentPackSubstitutionIndex;
3011 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3012 }
3013
3014 // If we didn't find the decl, then we must have a label decl that hasn't
3015 // been found yet. Lazily instantiate it and return it now.
3016 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00003017
Chris Lattner57ad3782011-02-17 20:34:02 +00003018 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3019 assert(Inst && "Failed to instantiate label??");
3020
3021 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3022 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003023 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003024
Douglas Gregore95b4092009-09-16 18:34:49 +00003025 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3026 if (!Record->isDependentContext())
3027 return D;
3028
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003029 // If the RecordDecl is actually the injected-class-name or a
3030 // "templated" declaration for a class template, class template
3031 // partial specialization, or a member class of a class template,
3032 // substitute into the injected-class-name of the class template
3033 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00003034 QualType T;
3035 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3036
3037 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00003038 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00003039 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3040 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00003041 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00003042
3043 // If we call SubstType with an InjectedClassNameType here we
3044 // can end up in an infinite loop.
3045 T = Context.getTypeDeclType(Record);
3046 assert(isa<InjectedClassNameType>(T) &&
3047 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00003048 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00003049 }
Douglas Gregore95b4092009-09-16 18:34:49 +00003050
3051 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003052 // Substitute into the injected-class-name to get the type
3053 // corresponding to the instantiation we want, which may also be
3054 // the current instantiation (if we're in a template
3055 // definition). This substitution should never fail, since we
3056 // know we can instantiate the injected-class-name or we
3057 // wouldn't have gotten to the injected-class-name!
3058
3059 // FIXME: Can we use the CurrentInstantiationScope to avoid this
3060 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00003061 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00003062 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
3063
3064 if (!T->isDependentType()) {
3065 assert(T->isRecordType() && "Instantiation must produce a record type");
3066 return T->getAs<RecordType>()->getDecl();
3067 }
3068
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003069 // We are performing "partial" template instantiation to create
3070 // the member declarations for the members of a class template
3071 // specialization. Therefore, D is actually referring to something
3072 // in the current instantiation. Look through the current
3073 // context, which contains actual instantiations, to find the
3074 // instantiation of the "current instantiation" that D refers
3075 // to.
3076 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003077 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00003078 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003079 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003080 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00003081 if (isInstantiationOf(ClassTemplate,
3082 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00003083 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003084
3085 if (!DC->isDependentContext())
3086 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00003087 }
3088
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003089 // We're performing "instantiation" of a member of the current
3090 // instantiation while we are type-checking the
3091 // definition. Compute the declaration context and return that.
3092 assert(!SawNonDependentContext &&
3093 "No dependent context while instantiating record");
3094 DeclContext *DC = computeDeclContext(T);
3095 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003096 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003097 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003098 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003099
Douglas Gregore95b4092009-09-16 18:34:49 +00003100 // Fall through to deal with other dependent record types (e.g.,
3101 // anonymous unions in class templates).
3102 }
John McCall52a575a2009-08-29 08:11:13 +00003103
Douglas Gregore95b4092009-09-16 18:34:49 +00003104 if (!ParentDC->isDependentContext())
3105 return D;
3106
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003107 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003108 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003109 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Douglas Gregor815215d2009-05-27 05:35:12 +00003111 if (ParentDC != D->getDeclContext()) {
3112 // We performed some kind of instantiation in the parent context,
3113 // so now we need to look into the instantiated parent context to
3114 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003115
John McCall3cb0ebd2010-03-10 03:28:59 +00003116 // If our context used to be dependent, we may need to instantiate
3117 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003118 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003119 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003120 if (!Spec->isDependentContext()) {
3121 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003122 const RecordType *Tag = T->getAs<RecordType>();
3123 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003124 if (Tag->isBeingDefined())
3125 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003126 if (!Tag->isBeingDefined() &&
3127 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3128 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003129
3130 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003131 }
3132 }
3133
Douglas Gregor815215d2009-05-27 05:35:12 +00003134 NamedDecl *Result = 0;
3135 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003136 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003137 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3138 } else {
3139 // Since we don't have a name for the entity we're looking for,
3140 // our only option is to walk through all of the declarations to
3141 // find that name. This will occur in a few cases:
3142 //
3143 // - anonymous struct/union within a template
3144 // - unnamed class/struct/union/enum within a template
3145 //
3146 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003147 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003148 ParentDC->decls_begin(),
3149 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003150 }
Mike Stump1eb44332009-09-09 15:08:12 +00003151
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003152 if (!Result) {
3153 if (isa<UsingShadowDecl>(D)) {
3154 // UsingShadowDecls can instantiate to nothing because of using hiding.
3155 } else if (Diags.hasErrorOccurred()) {
3156 // We've already complained about something, so most likely this
3157 // declaration failed to instantiate. There's no point in complaining
3158 // further, since this is normal in invalid code.
3159 } else if (IsBeingInstantiated) {
3160 // The class in which this member exists is currently being
3161 // instantiated, and we haven't gotten around to instantiating this
3162 // member yet. This can happen when the code uses forward declarations
3163 // of member classes, and introduces ordering dependencies via
3164 // template instantiation.
3165 Diag(Loc, diag::err_member_not_yet_instantiated)
3166 << D->getDeclName()
3167 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3168 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3169 } else {
3170 // We should have found something, but didn't.
3171 llvm_unreachable("Unable to find instantiation of declaration!");
3172 }
3173 }
3174
Douglas Gregor815215d2009-05-27 05:35:12 +00003175 D = Result;
3176 }
3177
Douglas Gregor815215d2009-05-27 05:35:12 +00003178 return D;
3179}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003180
Mike Stump1eb44332009-09-09 15:08:12 +00003181/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003182/// instantiations we have seen until this point.
Douglas Gregor78844032011-04-22 22:25:37 +00003183///
3184/// \returns true if anything was instantiated.
3185bool Sema::PerformPendingInstantiations(bool LocalOnly) {
3186 bool InstantiatedAnything = false;
Douglas Gregor60406be2010-01-16 22:29:39 +00003187 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003188 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003189 PendingImplicitInstantiation Inst;
3190
3191 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003192 Inst = PendingInstantiations.front();
3193 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003194 } else {
3195 Inst = PendingLocalImplicitInstantiations.front();
3196 PendingLocalImplicitInstantiations.pop_front();
3197 }
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Douglas Gregor7caa6822009-07-24 20:34:43 +00003199 // Instantiate function definitions
3200 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003201 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3202 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003203 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3204 TSK_ExplicitInstantiationDefinition;
3205 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3206 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003207 InstantiatedAnything = true;
Douglas Gregor7caa6822009-07-24 20:34:43 +00003208 continue;
3209 }
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Douglas Gregor7caa6822009-07-24 20:34:43 +00003211 // Instantiate static data member definitions.
3212 VarDecl *Var = cast<VarDecl>(Inst.first);
3213 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003214
Chandler Carruth291b4412010-02-13 10:17:50 +00003215 // Don't try to instantiate declarations if the most recent redeclaration
3216 // is invalid.
3217 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3218 continue;
3219
3220 // Check if the most recent declaration has changed the specialization kind
3221 // and removed the need for implicit instantiation.
3222 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3223 case TSK_Undeclared:
3224 assert(false && "Cannot instantitiate an undeclared specialization.");
3225 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003226 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003227 continue; // No longer need to instantiate this type.
3228 case TSK_ExplicitInstantiationDefinition:
3229 // We only need an instantiation if the pending instantiation *is* the
3230 // explicit instantiation.
3231 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003232 case TSK_ImplicitInstantiation:
3233 break;
3234 }
3235
John McCallf312b1e2010-08-26 23:41:50 +00003236 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3237 "instantiating static data member "
3238 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Chandler Carruth58e390e2010-08-25 08:27:02 +00003240 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3241 TSK_ExplicitInstantiationDefinition;
3242 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3243 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003244 InstantiatedAnything = true;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003245 }
Douglas Gregor78844032011-04-22 22:25:37 +00003246
3247 return InstantiatedAnything;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003248}
John McCall0c01d182010-03-24 05:22:00 +00003249
3250void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3251 const MultiLevelTemplateArgumentList &TemplateArgs) {
3252 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3253 E = Pattern->ddiag_end(); I != E; ++I) {
3254 DependentDiagnostic *DD = *I;
3255
3256 switch (DD->getKind()) {
3257 case DependentDiagnostic::Access:
3258 HandleDependentAccessCheck(*DD, TemplateArgs);
3259 break;
3260 }
3261 }
3262}