blob: 2c0c7ae90ff8a09eabb640cd4bb72a2952b397fb [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;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001219 if (Function->hasBody(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())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001251 if (RPattern->hasBody(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
Douglas Gregore53060f2009-06-25 22:08:12 +00001267 return Function;
1268}
1269
Douglas Gregord60e1052009-08-27 16:57:43 +00001270Decl *
1271TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1272 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001273 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1274 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001275 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001276 // We are creating a function template specialization from a function
1277 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001278 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001279 std::pair<const TemplateArgument *, unsigned> Innermost
1280 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001282 FunctionDecl *SpecFunc
1283 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1284 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Douglas Gregor6b906862009-08-21 00:16:32 +00001286 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001287 if (SpecFunc)
1288 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001289 }
1290
John McCallb0cb0222010-03-27 05:57:59 +00001291 bool isFriend;
1292 if (FunctionTemplate)
1293 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1294 else
1295 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1296
Douglas Gregor79c22782010-01-16 20:21:20 +00001297 bool MergeWithParentScope = (TemplateParams != 0) ||
1298 !(isa<Decl>(Owner) &&
1299 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001300 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001301
John McCall4eab39f2010-10-19 02:26:41 +00001302 // Instantiate enclosing template arguments for friends.
1303 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1304 unsigned NumTempParamLists = 0;
1305 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1306 TempParamLists.set_size(NumTempParamLists);
1307 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1308 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1309 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1310 if (!InstParams)
1311 return NULL;
1312 TempParamLists[I] = InstParams;
1313 }
1314 }
1315
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001316 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001317 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1318 TInfo = SubstFunctionType(D, Params);
1319 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001320 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001321 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001322
Abramo Bagnara723df242010-12-14 22:11:44 +00001323 // \brief If the type of this function, after ignoring parentheses,
1324 // is not *directly* a function type, then we're instantiating a function
1325 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001326 //
1327 // typedef int functype(int, int);
1328 // functype func;
1329 //
1330 // In this case, we'll just go instantiate the ParmVarDecls that we
1331 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001332 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001333 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001334 llvm::SmallVector<QualType, 4> ParamTypes;
1335 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1336 D->getNumParams(), TemplateArgs, ParamTypes,
1337 &Params))
1338 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001339 }
1340
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001341 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1342 if (QualifierLoc) {
1343 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001344 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001345 if (!QualifierLoc)
1346 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001347 }
1348
1349 DeclContext *DC = Owner;
1350 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001351 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001352 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001353 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001354 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001355
1356 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1357 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001358 } else {
1359 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1360 D->getDeclContext(),
1361 TemplateArgs);
1362 }
1363 if (!DC) return 0;
1364 }
1365
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001366 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001367 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001368 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001370 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001371 DeclarationNameInfo NameInfo
1372 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001373 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001374 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001375 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001376 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001377 Constructor->isInlineSpecified(),
Sean Huntad7ec122011-05-05 03:36:28 +00001378 false,
1379 Constructor->isExplicitlyDefaulted());
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 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001500
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001501 return Method;
1502}
1503
Douglas Gregor615c5d42009-03-24 16:43:20 +00001504Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001505 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001506}
1507
Douglas Gregor03b2b072009-03-24 00:15:49 +00001508Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001509 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001510}
1511
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001512Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001513 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001514}
1515
Douglas Gregor6477b692009-03-25 15:04:13 +00001516ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001517 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1518 llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001519}
1520
John McCalle29ba202009-08-20 01:44:21 +00001521Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1522 TemplateTypeParmDecl *D) {
1523 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001524 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001525
John McCalle29ba202009-08-20 01:44:21 +00001526 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001527 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1528 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001529 D->getDepth() - TemplateArgs.getNumLevels(),
1530 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001531 D->wasDeclaredWithTypename(),
1532 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001533 Inst->setAccess(AS_public);
1534
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001535 if (D->hasDefaultArgument())
1536 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001537
Douglas Gregor550d9b22009-10-31 17:21:17 +00001538 // Introduce this template parameter's instantiation into the instantiation
1539 // scope.
1540 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1541
John McCalle29ba202009-08-20 01:44:21 +00001542 return Inst;
1543}
1544
Douglas Gregor33642df2009-10-23 23:25:44 +00001545Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1546 NonTypeTemplateParmDecl *D) {
1547 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001548 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1549 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1550 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1551 bool IsExpandedParameterPack = false;
1552 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001553 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001554 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001555
1556 if (D->isExpandedParameterPack()) {
1557 // The non-type template parameter pack is an already-expanded pack
1558 // expansion of types. Substitute into each of the expanded types.
1559 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1560 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1561 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1562 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1563 TemplateArgs,
1564 D->getLocation(),
1565 D->getDeclName());
1566 if (!NewDI)
1567 return 0;
1568
1569 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1570 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1571 D->getLocation());
1572 if (NewT.isNull())
1573 return 0;
1574 ExpandedParameterPackTypes.push_back(NewT);
1575 }
1576
1577 IsExpandedParameterPack = true;
1578 DI = D->getTypeSourceInfo();
1579 T = DI->getType();
1580 } else if (isa<PackExpansionTypeLoc>(TL)) {
1581 // The non-type template parameter pack's type is a pack expansion of types.
1582 // Determine whether we need to expand this parameter pack into separate
1583 // types.
1584 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1585 TypeLoc Pattern = Expansion.getPatternLoc();
1586 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1587 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1588
1589 // Determine whether the set of unexpanded parameter packs can and should
1590 // be expanded.
1591 bool Expand = true;
1592 bool RetainExpansion = false;
1593 llvm::Optional<unsigned> OrigNumExpansions
1594 = Expansion.getTypePtr()->getNumExpansions();
1595 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1596 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1597 Pattern.getSourceRange(),
1598 Unexpanded.data(),
1599 Unexpanded.size(),
1600 TemplateArgs,
1601 Expand, RetainExpansion,
1602 NumExpansions))
1603 return 0;
1604
1605 if (Expand) {
1606 for (unsigned I = 0; I != *NumExpansions; ++I) {
1607 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1608 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1609 D->getLocation(),
1610 D->getDeclName());
1611 if (!NewDI)
1612 return 0;
1613
1614 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1615 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1616 NewDI->getType(),
1617 D->getLocation());
1618 if (NewT.isNull())
1619 return 0;
1620 ExpandedParameterPackTypes.push_back(NewT);
1621 }
1622
1623 // Note that we have an expanded parameter pack. The "type" of this
1624 // expanded parameter pack is the original expansion type, but callers
1625 // will end up using the expanded parameter pack types for type-checking.
1626 IsExpandedParameterPack = true;
1627 DI = D->getTypeSourceInfo();
1628 T = DI->getType();
1629 } else {
1630 // We cannot fully expand the pack expansion now, so substitute into the
1631 // pattern and create a new pack expansion type.
1632 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1633 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1634 D->getLocation(),
1635 D->getDeclName());
1636 if (!NewPattern)
1637 return 0;
1638
1639 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1640 NumExpansions);
1641 if (!DI)
1642 return 0;
1643
1644 T = DI->getType();
1645 }
1646 } else {
1647 // Simple case: substitution into a parameter that is not a parameter pack.
1648 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1649 D->getLocation(), D->getDeclName());
1650 if (!DI)
1651 return 0;
1652
1653 // Check that this type is acceptable for a non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001654 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1655 D->getLocation());
1656 if (T.isNull()) {
1657 T = SemaRef.Context.IntTy;
1658 Invalid = true;
1659 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001660 }
1661
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001662 NonTypeTemplateParmDecl *Param;
1663 if (IsExpandedParameterPack)
1664 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001665 D->getInnerLocStart(),
1666 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001667 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001668 D->getPosition(),
1669 D->getIdentifier(), T,
1670 DI,
1671 ExpandedParameterPackTypes.data(),
1672 ExpandedParameterPackTypes.size(),
1673 ExpandedParameterPackTypesAsWritten.data());
1674 else
1675 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001676 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001677 D->getLocation(),
1678 D->getDepth() - TemplateArgs.getNumLevels(),
1679 D->getPosition(),
1680 D->getIdentifier(), T,
1681 D->isParameterPack(), DI);
1682
Douglas Gregor9a299e02011-03-04 17:52:15 +00001683 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001684 if (Invalid)
1685 Param->setInvalidDecl();
1686
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001687 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001688
1689 // Introduce this template parameter's instantiation into the instantiation
1690 // scope.
1691 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001692 return Param;
1693}
1694
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001695Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001696TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1697 TemplateTemplateParmDecl *D) {
1698 // Instantiate the template parameter list of the template template parameter.
1699 TemplateParameterList *TempParams = D->getTemplateParameters();
1700 TemplateParameterList *InstParams;
1701 {
1702 // Perform the actual substitution of template parameters within a new,
1703 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001704 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001705 InstParams = SubstTemplateParams(TempParams);
1706 if (!InstParams)
1707 return NULL;
1708 }
1709
1710 // Build the template template parameter.
1711 TemplateTemplateParmDecl *Param
1712 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001713 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001714 D->getPosition(), D->isParameterPack(),
1715 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001716 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001717 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001718
Douglas Gregor9106ef72009-11-11 16:58:32 +00001719 // Introduce this template parameter's instantiation into the instantiation
1720 // scope.
1721 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1722
1723 return Param;
1724}
1725
Douglas Gregor48c32a72009-11-17 06:07:40 +00001726Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001727 // Using directives are never dependent (and never contain any types or
1728 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001729
1730 UsingDirectiveDecl *Inst
1731 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1732 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001733 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001734 D->getIdentLocation(),
1735 D->getNominatedNamespace(),
1736 D->getCommonAncestor());
1737 Owner->addDecl(Inst);
1738 return Inst;
1739}
1740
John McCalled976492009-12-04 22:46:56 +00001741Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001742
1743 // The nested name specifier may be dependent, for example
1744 // template <typename T> struct t {
1745 // struct s1 { T f1(); };
1746 // struct s2 : s1 { using s1::f1; };
1747 // };
1748 // template struct t<int>;
1749 // Here, in using s1::f1, s1 refers to t<T>::s1;
1750 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001751 NestedNameSpecifierLoc QualifierLoc
1752 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1753 TemplateArgs);
1754 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001755 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001756
1757 // The name info is non-dependent, so no transformation
1758 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001759 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001760
John McCall9f54ad42009-12-10 09:41:52 +00001761 // We only need to do redeclaration lookups if we're in a class
1762 // scope (in fact, it's not really even possible in non-class
1763 // scopes).
1764 bool CheckRedeclaration = Owner->isRecord();
1765
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001766 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1767 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001768
John McCalled976492009-12-04 22:46:56 +00001769 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001770 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001771 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001772 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001773 D->isTypeName());
1774
Douglas Gregor5149f372011-02-25 15:54:31 +00001775 CXXScopeSpec SS;
1776 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001777 if (CheckRedeclaration) {
1778 Prev.setHideTags(false);
1779 SemaRef.LookupQualifiedName(Prev, Owner);
1780
1781 // Check for invalid redeclarations.
1782 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1783 D->isTypeName(), SS,
1784 D->getLocation(), Prev))
1785 NewUD->setInvalidDecl();
1786
1787 }
1788
1789 if (!NewUD->isInvalidDecl() &&
1790 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001791 D->getLocation()))
1792 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001793
John McCalled976492009-12-04 22:46:56 +00001794 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1795 NewUD->setAccess(D->getAccess());
1796 Owner->addDecl(NewUD);
1797
John McCall9f54ad42009-12-10 09:41:52 +00001798 // Don't process the shadow decls for an invalid decl.
1799 if (NewUD->isInvalidDecl())
1800 return NewUD;
1801
John McCall323c3102009-12-22 22:26:37 +00001802 bool isFunctionScope = Owner->isFunctionOrMethod();
1803
John McCall9f54ad42009-12-10 09:41:52 +00001804 // Process the shadow decls.
1805 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1806 I != E; ++I) {
1807 UsingShadowDecl *Shadow = *I;
1808 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001809 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1810 Shadow->getLocation(),
1811 Shadow->getTargetDecl(),
1812 TemplateArgs));
1813 if (!InstTarget)
1814 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001815
1816 if (CheckRedeclaration &&
1817 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1818 continue;
1819
1820 UsingShadowDecl *InstShadow
1821 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1822 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001823
1824 if (isFunctionScope)
1825 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001826 }
John McCalled976492009-12-04 22:46:56 +00001827
1828 return NewUD;
1829}
1830
1831Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001832 // Ignore these; we handle them in bulk when processing the UsingDecl.
1833 return 0;
John McCalled976492009-12-04 22:46:56 +00001834}
1835
John McCall7ba107a2009-11-18 02:36:19 +00001836Decl * TemplateDeclInstantiator
1837 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001838 NestedNameSpecifierLoc QualifierLoc
1839 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1840 TemplateArgs);
1841 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001842 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001844 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001845 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001847 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1848 // Hence, no tranformation is required for it.
1849 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001850 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001851 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001852 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001853 /*instantiation*/ true,
1854 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001855 if (UD)
John McCalled976492009-12-04 22:46:56 +00001856 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1857
John McCall7ba107a2009-11-18 02:36:19 +00001858 return UD;
1859}
1860
1861Decl * TemplateDeclInstantiator
1862 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001863 NestedNameSpecifierLoc QualifierLoc
1864 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1865 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001866 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001867
John McCall7ba107a2009-11-18 02:36:19 +00001868 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001869 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001870
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001871 DeclarationNameInfo NameInfo
1872 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1873
John McCall7ba107a2009-11-18 02:36:19 +00001874 NamedDecl *UD =
1875 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001876 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001877 /*instantiation*/ true,
1878 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001879 if (UD)
John McCalled976492009-12-04 22:46:56 +00001880 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1881
Anders Carlsson0d8df782009-08-29 19:37:28 +00001882 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001883}
1884
John McCallce3ff2b2009-08-25 22:02:44 +00001885Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001886 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001887 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001888 if (D->isInvalidDecl())
1889 return 0;
1890
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001891 return Instantiator.Visit(D);
1892}
1893
John McCalle29ba202009-08-20 01:44:21 +00001894/// \brief Instantiates a nested template parameter list in the current
1895/// instantiation context.
1896///
1897/// \param L The parameter list to instantiate
1898///
1899/// \returns NULL if there was an error
1900TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001901TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001902 // Get errors for all the parameters before bailing out.
1903 bool Invalid = false;
1904
1905 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001906 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001907 ParamVector Params;
1908 Params.reserve(N);
1909 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1910 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001911 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001912 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001913 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001914 }
1915
1916 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001917 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001918 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001919
1920 TemplateParameterList *InstL
1921 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1922 L->getLAngleLoc(), &Params.front(), N,
1923 L->getRAngleLoc());
1924 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001925}
John McCalle29ba202009-08-20 01:44:21 +00001926
Douglas Gregored9c0f92009-10-29 00:04:11 +00001927/// \brief Instantiate the declaration of a class template partial
1928/// specialization.
1929///
1930/// \param ClassTemplate the (instantiated) class template that is partially
1931// specialized by the instantiation of \p PartialSpec.
1932///
1933/// \param PartialSpec the (uninstantiated) class template partial
1934/// specialization that we are instantiating.
1935///
Douglas Gregord65587f2010-11-10 19:44:59 +00001936/// \returns The instantiated partial specialization, if successful; otherwise,
1937/// NULL to indicate an error.
1938ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001939TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1940 ClassTemplateDecl *ClassTemplate,
1941 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001942 // Create a local instantiation scope for this class template partial
1943 // specialization, which will contain the instantiations of the template
1944 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001945 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001946
Douglas Gregored9c0f92009-10-29 00:04:11 +00001947 // Substitute into the template parameters of the class template partial
1948 // specialization.
1949 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1950 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1951 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001952 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001953
1954 // Substitute into the template arguments of the class template partial
1955 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001956 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001957 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1958 PartialSpec->getNumTemplateArgsAsWritten(),
1959 InstTemplateArgs, TemplateArgs))
1960 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001961
Douglas Gregored9c0f92009-10-29 00:04:11 +00001962 // Check that the template argument list is well-formed for this
1963 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001964 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001965 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1966 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001967 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001968 false,
1969 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001970 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001971
1972 // Figure out where to insert this class template partial specialization
1973 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001974 void *InsertPos = 0;
1975 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001976 = ClassTemplate->findPartialSpecialization(Converted.data(),
1977 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001978
1979 // Build the canonical type that describes the converted template
1980 // arguments of the class template partial specialization.
1981 QualType CanonType
1982 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001983 Converted.data(),
1984 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001985
1986 // Build the fully-sugared type for this class template
1987 // specialization as the user wrote in the specialization
1988 // itself. This means that we'll pretty-print the type retrieved
1989 // from the specialization's declaration the way that the user
1990 // actually wrote the specialization, rather than formatting the
1991 // name based on the "canonical" representation used to store the
1992 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001993 TypeSourceInfo *WrittenTy
1994 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1995 TemplateName(ClassTemplate),
1996 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001997 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001998 CanonType);
1999
2000 if (PrevDecl) {
2001 // We've already seen a partial specialization with the same template
2002 // parameters and template arguments. This can happen, for example, when
2003 // substituting the outer template arguments ends up causing two
2004 // class template partial specializations of a member class template
2005 // to have identical forms, e.g.,
2006 //
2007 // template<typename T, typename U>
2008 // struct Outer {
2009 // template<typename X, typename Y> struct Inner;
2010 // template<typename Y> struct Inner<T, Y>;
2011 // template<typename Y> struct Inner<U, Y>;
2012 // };
2013 //
2014 // Outer<int, int> outer; // error: the partial specializations of Inner
2015 // // have the same signature.
2016 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002017 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002018 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2019 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002020 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002021 }
2022
2023
2024 // Create the class template partial specialization declaration.
2025 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00002026 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2027 PartialSpec->getTagKind(),
2028 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002029 PartialSpec->getLocStart(),
2030 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002031 InstParams,
2032 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002033 Converted.data(),
2034 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002035 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002036 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002037 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002038 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002039 // Substitute the nested name specifier, if any.
2040 if (SubstQualifier(PartialSpec, InstPartialSpec))
2041 return 0;
2042
Douglas Gregored9c0f92009-10-29 00:04:11 +00002043 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002044 InstPartialSpec->setTypeAsWritten(WrittenTy);
2045
Douglas Gregored9c0f92009-10-29 00:04:11 +00002046 // Add this partial specialization to the set of class template partial
2047 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002048 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00002049 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002050}
2051
John McCall21ef0fa2010-03-11 09:03:00 +00002052TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002053TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002054 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002055 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2056 assert(OldTInfo && "substituting function without type source info");
2057 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002058 TypeSourceInfo *NewTInfo
2059 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2060 D->getTypeSpecStartLoc(),
2061 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002062 if (!NewTInfo)
2063 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002064
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002065 if (NewTInfo != OldTInfo) {
2066 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002067 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002068 if (FunctionProtoTypeLoc *OldProtoLoc
2069 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002070 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002071 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2072 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002073 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2074 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2075 OldIdx != NumOldParams; ++OldIdx) {
2076 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2077 if (!OldParam->isParameterPack() ||
2078 (NewIdx < NumNewParams &&
2079 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2080 // Simple case: normal parameter, or a parameter pack that's
2081 // instantiated to a (still-dependent) parameter pack.
2082 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2083 Params.push_back(NewParam);
2084 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2085 NewParam);
2086 continue;
2087 }
2088
2089 // Parameter pack: make the instantiation an argument pack.
2090 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2091 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002092 unsigned NumArgumentsInExpansion
2093 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2094 TemplateArgs);
2095 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002096 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2097 Params.push_back(NewParam);
2098 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2099 NewParam);
2100 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002101 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002102 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002103 } else {
2104 // The function type itself was not dependent and therefore no
2105 // substitution occurred. However, we still need to instantiate
2106 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002107 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002108 if (FunctionProtoTypeLoc *OldProtoLoc
2109 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2110 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2111 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2112 if (!Parm)
2113 return 0;
2114 Params.push_back(Parm);
2115 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002116 }
2117 }
John McCall21ef0fa2010-03-11 09:03:00 +00002118 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002119}
2120
Mike Stump1eb44332009-09-09 15:08:12 +00002121/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002122/// declaration (New) from the corresponding fields of its template (Tmpl).
2123///
2124/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002125bool
2126TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002127 FunctionDecl *Tmpl) {
2128 if (Tmpl->isDeleted())
2129 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregorcca9e962009-07-01 22:01:06 +00002131 // If we are performing substituting explicitly-specified template arguments
2132 // or deduced template arguments into a function template and we reach this
2133 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002134 // to keeping the new function template specialization. We therefore
2135 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002136 // into a template instantiation for this specific function template
2137 // specialization, which is not a SFINAE context, so that we diagnose any
2138 // further errors in the declaration itself.
2139 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2140 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2141 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2142 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002143 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002144 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002145 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002146 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002147 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002148 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2149 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002150 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002151 }
2152 }
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002154 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2155 assert(Proto && "Function template without prototype?");
2156
Sebastian Redl60618fa2011-03-12 11:50:43 +00002157 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002158 // The function has an exception specification or a "noreturn"
2159 // attribute. Substitute into each of the exception types.
2160 llvm::SmallVector<QualType, 4> Exceptions;
2161 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2162 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002163 if (const PackExpansionType *PackExpansion
2164 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2165 // We have a pack expansion. Instantiate it.
2166 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2167 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2168 Unexpanded);
2169 assert(!Unexpanded.empty() &&
2170 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002171
Douglas Gregorb99268b2010-12-21 00:52:54 +00002172 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002173 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002174 llvm::Optional<unsigned> NumExpansions
2175 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002176 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2177 SourceRange(),
2178 Unexpanded.data(),
2179 Unexpanded.size(),
2180 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002181 Expand,
2182 RetainExpansion,
2183 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002184 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002185
Douglas Gregorb99268b2010-12-21 00:52:54 +00002186 if (!Expand) {
2187 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002188 // just substitute into the pattern and create a new pack expansion
2189 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002190 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2191 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2192 TemplateArgs,
2193 New->getLocation(), New->getDeclName());
2194 if (T.isNull())
2195 break;
2196
Douglas Gregorcded4f62011-01-14 17:04:44 +00002197 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002198 Exceptions.push_back(T);
2199 continue;
2200 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002201
Douglas Gregorb99268b2010-12-21 00:52:54 +00002202 // Substitute into the pack expansion pattern for each template
2203 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002204 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002205 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2206
2207 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2208 TemplateArgs,
2209 New->getLocation(), New->getDeclName());
2210 if (T.isNull()) {
2211 Invalid = true;
2212 break;
2213 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002214
Douglas Gregorb99268b2010-12-21 00:52:54 +00002215 Exceptions.push_back(T);
2216 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002217
Douglas Gregorb99268b2010-12-21 00:52:54 +00002218 if (Invalid)
2219 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002220
Douglas Gregorb99268b2010-12-21 00:52:54 +00002221 continue;
2222 }
2223
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002224 QualType T
2225 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2226 New->getLocation(), New->getDeclName());
2227 if (T.isNull() ||
2228 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2229 continue;
2230
2231 Exceptions.push_back(T);
2232 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002233 Expr *NoexceptExpr = 0;
2234 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2235 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2236 if (E.isUsable())
2237 NoexceptExpr = E.take();
2238 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002239
2240 // Rebuild the function type
2241
John McCalle23cf432010-12-14 08:05:40 +00002242 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002243 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002244 EPI.NumExceptions = Exceptions.size();
2245 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002246 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002247 EPI.ExtInfo = Proto->getExtInfo();
2248
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002249 const FunctionProtoType *NewProto
2250 = New->getType()->getAs<FunctionProtoType>();
2251 assert(NewProto && "Template instantiation without function prototype?");
2252 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2253 NewProto->arg_type_begin(),
2254 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002255 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002256 }
2257
John McCall1d8d1cc2010-08-01 02:01:53 +00002258 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002259
Douglas Gregore53060f2009-06-25 22:08:12 +00002260 return false;
2261}
2262
Douglas Gregor5545e162009-03-24 00:38:23 +00002263/// \brief Initializes common fields of an instantiated method
2264/// declaration (New) from the corresponding fields of its template
2265/// (Tmpl).
2266///
2267/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002268bool
2269TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002270 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002271 if (InitFunctionInstantiation(New, Tmpl))
2272 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregor5545e162009-03-24 00:38:23 +00002274 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002275 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002276 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002277
2278 // FIXME: attributes
2279 // FIXME: New needs a pointer to Tmpl
2280 return false;
2281}
Douglas Gregora58861f2009-05-13 20:28:22 +00002282
2283/// \brief Instantiate the definition of the given function from its
2284/// template.
2285///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002286/// \param PointOfInstantiation the point at which the instantiation was
2287/// required. Note that this is not precisely a "point of instantiation"
2288/// for the function, but it's close.
2289///
Douglas Gregora58861f2009-05-13 20:28:22 +00002290/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002291/// function template specialization or member function of a class template
2292/// specialization.
2293///
2294/// \param Recursive if true, recursively instantiates any functions that
2295/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002296///
2297/// \param DefinitionRequired if true, then we are performing an explicit
2298/// instantiation where the body of the function is required. Complain if
2299/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002300void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002301 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002302 bool Recursive,
2303 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002304 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002305 return;
2306
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002307 // Never instantiate an explicit specialization.
2308 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2309 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002310
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002311 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002312 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002313 Stmt *Pattern = 0;
2314 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002315 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002316
Francois Pichet8387e2a2011-04-22 22:18:13 +00002317 // Postpone late parsed template instantiations.
2318 if (PatternDecl->isLateTemplateParsed() && !LateTemplateParser) {
2319 PendingInstantiations.push_back(
2320 std::make_pair(Function, PointOfInstantiation));
2321 return;
2322 }
2323
2324 // Call the LateTemplateParser callback if there a need to late parse
2325 // a templated function definition.
2326 if (!Pattern && PatternDecl && PatternDecl->isLateTemplateParsed() &&
2327 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002328 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002329 Pattern = PatternDecl->getBody(PatternDecl);
2330 }
2331
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002332 if (!Pattern) {
2333 if (DefinitionRequired) {
2334 if (Function->getPrimaryTemplate())
2335 Diag(PointOfInstantiation,
2336 diag::err_explicit_instantiation_undefined_func_template)
2337 << Function->getPrimaryTemplate();
2338 else
2339 Diag(PointOfInstantiation,
2340 diag::err_explicit_instantiation_undefined_member)
2341 << 1 << Function->getDeclName() << Function->getDeclContext();
2342
2343 if (PatternDecl)
2344 Diag(PatternDecl->getLocation(),
2345 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002346 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002347 } else if (Function->getTemplateSpecializationKind()
2348 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002349 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002350 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002351 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002352
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002353 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002354 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002355
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002356 // C++0x [temp.explicit]p9:
2357 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002358 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002359 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002360 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002361 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002362 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002363 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002365 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2366 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002367 return;
2368
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002369 // If we're performing recursive template instantiation, create our own
2370 // queue of pending implicit instantiations that we will instantiate later,
2371 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002372 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002373 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002374 if (Recursive) {
2375 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002376 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002377 }
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor9679caf2010-05-12 17:27:19 +00002379 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002380 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002381 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002382
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002383 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002384 // recorded, unless we're actually a member function within a local
2385 // class, in which case we need to merge our results with the parent
2386 // scope (of the enclosing function).
2387 bool MergeWithParentScope = false;
2388 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2389 MergeWithParentScope = Rec->isLocalClass();
2390
2391 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002393 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002394 // instantiation scope, and set the parameter names to those used
2395 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002396 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002397 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2398 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002399 if (!PatternParam->isParameterPack()) {
2400 // Simple case: not a parameter pack.
2401 assert(FParamIdx < Function->getNumParams());
2402 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2403 FunctionParam->setDeclName(PatternParam->getDeclName());
2404 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2405 ++FParamIdx;
2406 continue;
2407 }
2408
2409 // Expand the parameter pack.
2410 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2411 for (unsigned NumFParams = Function->getNumParams();
2412 FParamIdx < NumFParams;
2413 ++FParamIdx) {
2414 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2415 FunctionParam->setDeclName(PatternParam->getDeclName());
2416 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2417 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002418 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002419
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002420 // Enter the scope of this instantiation. We don't use
2421 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002422 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002423
Mike Stump1eb44332009-09-09 15:08:12 +00002424 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002425 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002426
2427 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002428 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002429 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2430 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2431 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002432 }
2433
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002434 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002435 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002436
Douglas Gregor52604ab2009-09-11 21:19:12 +00002437 if (Body.isInvalid())
2438 Function->setInvalidDecl();
2439
John McCall9ae2f072010-08-23 23:25:46 +00002440 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002441 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002442
John McCall0c01d182010-03-24 05:22:00 +00002443 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2444
John McCalleee1d542011-02-14 07:13:47 +00002445 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002446
2447 DeclGroupRef DG(Function);
2448 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor60406be2010-01-16 22:29:39 +00002450 // This class may have local implicit instantiations that need to be
2451 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002452 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002453 Scope.Exit();
2454
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002455 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002456 // Define any pending vtables.
2457 DefineUsedVTables();
2458
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002459 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002460 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002461 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002463 // Restore the set of pending vtables.
2464 VTableUses.swap(SavedVTableUses);
2465
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002466 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002467 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002468 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002469}
2470
2471/// \brief Instantiate the definition of the given variable from its
2472/// template.
2473///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002474/// \param PointOfInstantiation the point at which the instantiation was
2475/// required. Note that this is not precisely a "point of instantiation"
2476/// for the function, but it's close.
2477///
2478/// \param Var the already-instantiated declaration of a static member
2479/// variable of a class template specialization.
2480///
2481/// \param Recursive if true, recursively instantiates any functions that
2482/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002483///
2484/// \param DefinitionRequired if true, then we are performing an explicit
2485/// instantiation where an out-of-line definition of the member variable
2486/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002487void Sema::InstantiateStaticDataMemberDefinition(
2488 SourceLocation PointOfInstantiation,
2489 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002490 bool Recursive,
2491 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002492 if (Var->isInvalidDecl())
2493 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Douglas Gregor7caa6822009-07-24 20:34:43 +00002495 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002496 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002497 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002498 assert(Def->isStaticDataMember() && "Not a static data member?");
2499 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Douglas Gregor0d035142009-10-27 18:42:08 +00002501 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002502 // We did not find an out-of-line definition of this static data member,
2503 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002504 // instantiate this definition (or provide a specialization for it) in
2505 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002506 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002507 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002508 Diag(PointOfInstantiation,
2509 diag::err_explicit_instantiation_undefined_member)
2510 << 2 << Var->getDeclName() << Var->getDeclContext();
2511 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002512 } else if (Var->getTemplateSpecializationKind()
2513 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002514 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002515 std::make_pair(Var, PointOfInstantiation));
2516 }
2517
Douglas Gregor7caa6822009-07-24 20:34:43 +00002518 return;
2519 }
2520
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002521 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002522 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002523 return;
2524
2525 // C++0x [temp.explicit]p9:
2526 // Except for inline functions, other explicit instantiation declarations
2527 // have the effect of suppressing the implicit instantiation of the entity
2528 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002529 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002530 == TSK_ExplicitInstantiationDeclaration)
2531 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor7caa6822009-07-24 20:34:43 +00002533 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2534 if (Inst)
2535 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Douglas Gregor7caa6822009-07-24 20:34:43 +00002537 // If we're performing recursive template instantiation, create our own
2538 // queue of pending implicit instantiations that we will instantiate later,
2539 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002540 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002541 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002542 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregor7caa6822009-07-24 20:34:43 +00002544 // Enter the scope of this instantiation. We don't use
2545 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002546 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002548 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002549 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002550 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002551
2552 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002553
2554 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002555 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2556 assert(MSInfo && "Missing member specialization information?");
2557 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2558 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002559 DeclGroupRef DG(Var);
2560 Consumer.HandleTopLevelDecl(DG);
2561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregor7caa6822009-07-24 20:34:43 +00002563 if (Recursive) {
2564 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002565 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002566 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Douglas Gregor7caa6822009-07-24 20:34:43 +00002568 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002569 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002570 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002571}
Douglas Gregor815215d2009-05-27 05:35:12 +00002572
Anders Carlsson09025312009-08-29 05:16:22 +00002573void
2574Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2575 const CXXConstructorDecl *Tmpl,
2576 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Anders Carlsson09025312009-08-29 05:16:22 +00002578 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002579 bool AnyErrors = false;
2580
Anders Carlsson09025312009-08-29 05:16:22 +00002581 // Instantiate all the initializers.
2582 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002583 InitsEnd = Tmpl->init_end();
2584 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002585 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002586
Chandler Carruth030ef472010-09-03 21:54:20 +00002587 // Only instantiate written initializers, let Sema re-construct implicit
2588 // ones.
2589 if (!Init->isWritten())
2590 continue;
2591
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002592 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002593 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002595 SourceLocation EllipsisLoc;
2596
2597 if (Init->isPackExpansion()) {
2598 // This is a pack expansion. We should expand it now.
2599 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2600 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2601 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2602 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002603 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002604 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002605 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2606 BaseTL.getSourceRange(),
2607 Unexpanded.data(),
2608 Unexpanded.size(),
2609 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002610 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002611 NumExpansions)) {
2612 AnyErrors = true;
2613 New->setInvalidDecl();
2614 continue;
2615 }
2616 assert(ShouldExpand && "Partial instantiation of base initializer?");
2617
2618 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002619 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002620 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2621
2622 // Instantiate the initializer.
2623 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2624 LParenLoc, NewArgs, RParenLoc)) {
2625 AnyErrors = true;
2626 break;
2627 }
2628
2629 // Instantiate the base type.
2630 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2631 TemplateArgs,
2632 Init->getSourceLocation(),
2633 New->getDeclName());
2634 if (!BaseTInfo) {
2635 AnyErrors = true;
2636 break;
2637 }
2638
2639 // Build the initializer.
2640 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2641 BaseTInfo,
2642 (Expr **)NewArgs.data(),
2643 NewArgs.size(),
2644 Init->getLParenLoc(),
2645 Init->getRParenLoc(),
2646 New->getParent(),
2647 SourceLocation());
2648 if (NewInit.isInvalid()) {
2649 AnyErrors = true;
2650 break;
2651 }
2652
2653 NewInits.push_back(NewInit.get());
2654 NewArgs.clear();
2655 }
2656
2657 continue;
2658 }
2659
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002660 // Instantiate the initializer.
2661 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002662 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002663 AnyErrors = true;
2664 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002665 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002666
Anders Carlsson09025312009-08-29 05:16:22 +00002667 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002668 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002669 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002670 TemplateArgs,
2671 Init->getSourceLocation(),
2672 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002673 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002674 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002675 New->setInvalidDecl();
2676 continue;
2677 }
2678
John McCalla93c9342009-12-07 02:54:59 +00002679 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002680 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002681 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002682 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002683 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002684 New->getParent(),
2685 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002686 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002687 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002688 Init->getMemberLocation(),
2689 Init->getMember(),
2690 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002691 if (!Member) {
2692 AnyErrors = true;
2693 New->setInvalidDecl();
2694 continue;
2695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
2697 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002698 NewArgs.size(),
2699 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002700 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002701 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002702 } else if (Init->isIndirectMemberInitializer()) {
2703 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002704 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002705 Init->getMemberLocation(),
2706 Init->getIndirectMember(), TemplateArgs));
2707
Douglas Gregorb7107222011-03-04 19:46:35 +00002708 if (!IndirectMember) {
2709 AnyErrors = true;
2710 New->setInvalidDecl();
2711 continue;
2712 }
2713
Francois Pichet00eb3f92010-12-04 09:14:42 +00002714 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2715 NewArgs.size(),
2716 Init->getSourceLocation(),
2717 Init->getLParenLoc(),
2718 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002719 }
2720
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002721 if (NewInit.isInvalid()) {
2722 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002723 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002724 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002725 // FIXME: It would be nice if ASTOwningVector had a release function.
2726 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Anders Carlsson09025312009-08-29 05:16:22 +00002728 NewInits.push_back((MemInitTy *)NewInit.get());
2729 }
2730 }
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Anders Carlsson09025312009-08-29 05:16:22 +00002732 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002733 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002734 /*FIXME: ColonLoc */
2735 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002736 NewInits.data(), NewInits.size(),
2737 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002738}
2739
John McCall52a575a2009-08-29 08:11:13 +00002740// TODO: this could be templated if the various decl types used the
2741// same method name.
2742static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2743 ClassTemplateDecl *Instance) {
2744 Pattern = Pattern->getCanonicalDecl();
2745
2746 do {
2747 Instance = Instance->getCanonicalDecl();
2748 if (Pattern == Instance) return true;
2749 Instance = Instance->getInstantiatedFromMemberTemplate();
2750 } while (Instance);
2751
2752 return false;
2753}
2754
Douglas Gregor0d696532009-09-28 06:34:35 +00002755static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2756 FunctionTemplateDecl *Instance) {
2757 Pattern = Pattern->getCanonicalDecl();
2758
2759 do {
2760 Instance = Instance->getCanonicalDecl();
2761 if (Pattern == Instance) return true;
2762 Instance = Instance->getInstantiatedFromMemberTemplate();
2763 } while (Instance);
2764
2765 return false;
2766}
2767
Douglas Gregored9c0f92009-10-29 00:04:11 +00002768static bool
2769isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2770 ClassTemplatePartialSpecializationDecl *Instance) {
2771 Pattern
2772 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2773 do {
2774 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2775 Instance->getCanonicalDecl());
2776 if (Pattern == Instance)
2777 return true;
2778 Instance = Instance->getInstantiatedFromMember();
2779 } while (Instance);
2780
2781 return false;
2782}
2783
John McCall52a575a2009-08-29 08:11:13 +00002784static bool isInstantiationOf(CXXRecordDecl *Pattern,
2785 CXXRecordDecl *Instance) {
2786 Pattern = Pattern->getCanonicalDecl();
2787
2788 do {
2789 Instance = Instance->getCanonicalDecl();
2790 if (Pattern == Instance) return true;
2791 Instance = Instance->getInstantiatedFromMemberClass();
2792 } while (Instance);
2793
2794 return false;
2795}
2796
2797static bool isInstantiationOf(FunctionDecl *Pattern,
2798 FunctionDecl *Instance) {
2799 Pattern = Pattern->getCanonicalDecl();
2800
2801 do {
2802 Instance = Instance->getCanonicalDecl();
2803 if (Pattern == Instance) return true;
2804 Instance = Instance->getInstantiatedFromMemberFunction();
2805 } while (Instance);
2806
2807 return false;
2808}
2809
2810static bool isInstantiationOf(EnumDecl *Pattern,
2811 EnumDecl *Instance) {
2812 Pattern = Pattern->getCanonicalDecl();
2813
2814 do {
2815 Instance = Instance->getCanonicalDecl();
2816 if (Pattern == Instance) return true;
2817 Instance = Instance->getInstantiatedFromMemberEnum();
2818 } while (Instance);
2819
2820 return false;
2821}
2822
John McCalled976492009-12-04 22:46:56 +00002823static bool isInstantiationOf(UsingShadowDecl *Pattern,
2824 UsingShadowDecl *Instance,
2825 ASTContext &C) {
2826 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2827}
2828
2829static bool isInstantiationOf(UsingDecl *Pattern,
2830 UsingDecl *Instance,
2831 ASTContext &C) {
2832 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2833}
2834
John McCall7ba107a2009-11-18 02:36:19 +00002835static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2836 UsingDecl *Instance,
2837 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002838 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002839}
2840
2841static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002842 UsingDecl *Instance,
2843 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002844 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002845}
2846
John McCall52a575a2009-08-29 08:11:13 +00002847static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2848 VarDecl *Instance) {
2849 assert(Instance->isStaticDataMember());
2850
2851 Pattern = Pattern->getCanonicalDecl();
2852
2853 do {
2854 Instance = Instance->getCanonicalDecl();
2855 if (Pattern == Instance) return true;
2856 Instance = Instance->getInstantiatedFromStaticDataMember();
2857 } while (Instance);
2858
2859 return false;
2860}
2861
John McCalled976492009-12-04 22:46:56 +00002862// Other is the prospective instantiation
2863// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002864static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002865 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002866 if (UnresolvedUsingTypenameDecl *UUD
2867 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2868 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2869 return isInstantiationOf(UUD, UD, Ctx);
2870 }
2871 }
2872
2873 if (UnresolvedUsingValueDecl *UUD
2874 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002875 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2876 return isInstantiationOf(UUD, UD, Ctx);
2877 }
2878 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002879
Anders Carlsson0d8df782009-08-29 19:37:28 +00002880 return false;
2881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
John McCall52a575a2009-08-29 08:11:13 +00002883 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2884 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002885
John McCall52a575a2009-08-29 08:11:13 +00002886 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2887 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002888
John McCall52a575a2009-08-29 08:11:13 +00002889 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2890 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002891
Douglas Gregor7caa6822009-07-24 20:34:43 +00002892 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002893 if (Var->isStaticDataMember())
2894 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2895
2896 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2897 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002898
Douglas Gregor0d696532009-09-28 06:34:35 +00002899 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2900 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2901
Douglas Gregored9c0f92009-10-29 00:04:11 +00002902 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2903 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2904 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2905 PartialSpec);
2906
Anders Carlssond8b285f2009-09-01 04:26:58 +00002907 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2908 if (!Field->getDeclName()) {
2909 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002910 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002911 cast<FieldDecl>(D);
2912 }
2913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCalled976492009-12-04 22:46:56 +00002915 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2916 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2917
2918 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2919 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2920
Douglas Gregor815215d2009-05-27 05:35:12 +00002921 return D->getDeclName() && isa<NamedDecl>(Other) &&
2922 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2923}
2924
2925template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002926static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002927 NamedDecl *D,
2928 ForwardIterator first,
2929 ForwardIterator last) {
2930 for (; first != last; ++first)
2931 if (isInstantiationOf(Ctx, D, *first))
2932 return cast<NamedDecl>(*first);
2933
2934 return 0;
2935}
2936
John McCall02cace72009-08-28 07:59:38 +00002937/// \brief Finds the instantiation of the given declaration context
2938/// within the current instantiation.
2939///
2940/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002941DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002942 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002943 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002944 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002945 return cast_or_null<DeclContext>(ID);
2946 } else return DC;
2947}
2948
Douglas Gregored961e72009-05-27 17:54:46 +00002949/// \brief Find the instantiation of the given declaration within the
2950/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002951///
2952/// This routine is intended to be used when \p D is a declaration
2953/// referenced from within a template, that needs to mapped into the
2954/// corresponding declaration within an instantiation. For example,
2955/// given:
2956///
2957/// \code
2958/// template<typename T>
2959/// struct X {
2960/// enum Kind {
2961/// KnownValue = sizeof(T)
2962/// };
2963///
2964/// bool getKind() const { return KnownValue; }
2965/// };
2966///
2967/// template struct X<int>;
2968/// \endcode
2969///
2970/// In the instantiation of X<int>::getKind(), we need to map the
2971/// EnumConstantDecl for KnownValue (which refers to
2972/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002973/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2974/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002975NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002976 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002977 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002978 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002979 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002980 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002981 // D is a local of some kind. Look into the map of local
2982 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002983 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2984 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2985 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002986
Chris Lattner57ad3782011-02-17 20:34:02 +00002987 if (Found) {
2988 if (Decl *FD = Found->dyn_cast<Decl *>())
2989 return cast<NamedDecl>(FD);
2990
2991 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2992 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2993 }
2994
2995 // If we didn't find the decl, then we must have a label decl that hasn't
2996 // been found yet. Lazily instantiate it and return it now.
2997 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002998
Chris Lattner57ad3782011-02-17 20:34:02 +00002999 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3000 assert(Inst && "Failed to instantiate label??");
3001
3002 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3003 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003004 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003005
Douglas Gregore95b4092009-09-16 18:34:49 +00003006 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3007 if (!Record->isDependentContext())
3008 return D;
3009
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003010 // If the RecordDecl is actually the injected-class-name or a
3011 // "templated" declaration for a class template, class template
3012 // partial specialization, or a member class of a class template,
3013 // substitute into the injected-class-name of the class template
3014 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00003015 QualType T;
3016 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3017
3018 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00003019 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00003020 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3021 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00003022 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00003023
3024 // If we call SubstType with an InjectedClassNameType here we
3025 // can end up in an infinite loop.
3026 T = Context.getTypeDeclType(Record);
3027 assert(isa<InjectedClassNameType>(T) &&
3028 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00003029 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00003030 }
Douglas Gregore95b4092009-09-16 18:34:49 +00003031
3032 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003033 // Substitute into the injected-class-name to get the type
3034 // corresponding to the instantiation we want, which may also be
3035 // the current instantiation (if we're in a template
3036 // definition). This substitution should never fail, since we
3037 // know we can instantiate the injected-class-name or we
3038 // wouldn't have gotten to the injected-class-name!
3039
3040 // FIXME: Can we use the CurrentInstantiationScope to avoid this
3041 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00003042 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00003043 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
3044
3045 if (!T->isDependentType()) {
3046 assert(T->isRecordType() && "Instantiation must produce a record type");
3047 return T->getAs<RecordType>()->getDecl();
3048 }
3049
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003050 // We are performing "partial" template instantiation to create
3051 // the member declarations for the members of a class template
3052 // specialization. Therefore, D is actually referring to something
3053 // in the current instantiation. Look through the current
3054 // context, which contains actual instantiations, to find the
3055 // instantiation of the "current instantiation" that D refers
3056 // to.
3057 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003058 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00003059 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003060 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003061 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00003062 if (isInstantiationOf(ClassTemplate,
3063 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00003064 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003065
3066 if (!DC->isDependentContext())
3067 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00003068 }
3069
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003070 // We're performing "instantiation" of a member of the current
3071 // instantiation while we are type-checking the
3072 // definition. Compute the declaration context and return that.
3073 assert(!SawNonDependentContext &&
3074 "No dependent context while instantiating record");
3075 DeclContext *DC = computeDeclContext(T);
3076 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003077 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003078 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003079 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003080
Douglas Gregore95b4092009-09-16 18:34:49 +00003081 // Fall through to deal with other dependent record types (e.g.,
3082 // anonymous unions in class templates).
3083 }
John McCall52a575a2009-08-29 08:11:13 +00003084
Douglas Gregore95b4092009-09-16 18:34:49 +00003085 if (!ParentDC->isDependentContext())
3086 return D;
3087
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003088 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003089 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003090 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Douglas Gregor815215d2009-05-27 05:35:12 +00003092 if (ParentDC != D->getDeclContext()) {
3093 // We performed some kind of instantiation in the parent context,
3094 // so now we need to look into the instantiated parent context to
3095 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003096
John McCall3cb0ebd2010-03-10 03:28:59 +00003097 // If our context used to be dependent, we may need to instantiate
3098 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003099 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003100 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003101 if (!Spec->isDependentContext()) {
3102 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003103 const RecordType *Tag = T->getAs<RecordType>();
3104 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003105 if (Tag->isBeingDefined())
3106 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003107 if (!Tag->isBeingDefined() &&
3108 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3109 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003110
3111 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003112 }
3113 }
3114
Douglas Gregor815215d2009-05-27 05:35:12 +00003115 NamedDecl *Result = 0;
3116 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003117 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003118 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3119 } else {
3120 // Since we don't have a name for the entity we're looking for,
3121 // our only option is to walk through all of the declarations to
3122 // find that name. This will occur in a few cases:
3123 //
3124 // - anonymous struct/union within a template
3125 // - unnamed class/struct/union/enum within a template
3126 //
3127 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003128 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003129 ParentDC->decls_begin(),
3130 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003131 }
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003133 if (!Result) {
3134 if (isa<UsingShadowDecl>(D)) {
3135 // UsingShadowDecls can instantiate to nothing because of using hiding.
3136 } else if (Diags.hasErrorOccurred()) {
3137 // We've already complained about something, so most likely this
3138 // declaration failed to instantiate. There's no point in complaining
3139 // further, since this is normal in invalid code.
3140 } else if (IsBeingInstantiated) {
3141 // The class in which this member exists is currently being
3142 // instantiated, and we haven't gotten around to instantiating this
3143 // member yet. This can happen when the code uses forward declarations
3144 // of member classes, and introduces ordering dependencies via
3145 // template instantiation.
3146 Diag(Loc, diag::err_member_not_yet_instantiated)
3147 << D->getDeclName()
3148 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3149 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3150 } else {
3151 // We should have found something, but didn't.
3152 llvm_unreachable("Unable to find instantiation of declaration!");
3153 }
3154 }
3155
Douglas Gregor815215d2009-05-27 05:35:12 +00003156 D = Result;
3157 }
3158
Douglas Gregor815215d2009-05-27 05:35:12 +00003159 return D;
3160}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003161
Mike Stump1eb44332009-09-09 15:08:12 +00003162/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003163/// instantiations we have seen until this point.
Douglas Gregor78844032011-04-22 22:25:37 +00003164///
3165/// \returns true if anything was instantiated.
3166bool Sema::PerformPendingInstantiations(bool LocalOnly) {
3167 bool InstantiatedAnything = false;
Douglas Gregor60406be2010-01-16 22:29:39 +00003168 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003169 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003170 PendingImplicitInstantiation Inst;
3171
3172 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003173 Inst = PendingInstantiations.front();
3174 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003175 } else {
3176 Inst = PendingLocalImplicitInstantiations.front();
3177 PendingLocalImplicitInstantiations.pop_front();
3178 }
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Douglas Gregor7caa6822009-07-24 20:34:43 +00003180 // Instantiate function definitions
3181 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003182 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3183 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003184 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3185 TSK_ExplicitInstantiationDefinition;
3186 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3187 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003188 InstantiatedAnything = true;
Douglas Gregor7caa6822009-07-24 20:34:43 +00003189 continue;
3190 }
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Douglas Gregor7caa6822009-07-24 20:34:43 +00003192 // Instantiate static data member definitions.
3193 VarDecl *Var = cast<VarDecl>(Inst.first);
3194 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003195
Chandler Carruth291b4412010-02-13 10:17:50 +00003196 // Don't try to instantiate declarations if the most recent redeclaration
3197 // is invalid.
3198 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3199 continue;
3200
3201 // Check if the most recent declaration has changed the specialization kind
3202 // and removed the need for implicit instantiation.
3203 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3204 case TSK_Undeclared:
3205 assert(false && "Cannot instantitiate an undeclared specialization.");
3206 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003207 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003208 continue; // No longer need to instantiate this type.
3209 case TSK_ExplicitInstantiationDefinition:
3210 // We only need an instantiation if the pending instantiation *is* the
3211 // explicit instantiation.
3212 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003213 case TSK_ImplicitInstantiation:
3214 break;
3215 }
3216
John McCallf312b1e2010-08-26 23:41:50 +00003217 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3218 "instantiating static data member "
3219 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Chandler Carruth58e390e2010-08-25 08:27:02 +00003221 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3222 TSK_ExplicitInstantiationDefinition;
3223 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3224 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003225 InstantiatedAnything = true;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003226 }
Douglas Gregor78844032011-04-22 22:25:37 +00003227
3228 return InstantiatedAnything;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003229}
John McCall0c01d182010-03-24 05:22:00 +00003230
3231void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3232 const MultiLevelTemplateArgumentList &TemplateArgs) {
3233 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3234 E = Pattern->ddiag_end(); I != E; ++I) {
3235 DependentDiagnostic *DD = *I;
3236
3237 switch (DD->getKind()) {
3238 case DependentDiagnostic::Access:
3239 HandleDependentAccessCheck(*DD, TemplateArgs);
3240 break;
3241 }
3242 }
3243}