blob: 6fa208f6f85cf63f42f7556063c15d8636f7af0e [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 Smith162e1c12011-04-15 14:24:37 +0000131Decl *TemplateDeclInstantiator::VisitTypedefNameDecl(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());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000181 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000183 return Typedef;
184}
185
Richard Smith162e1c12011-04-15 14:24:37 +0000186Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
187 return VisitTypedefNameDecl(D, /*IsTypeAlias=*/false);
188}
189
190Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
191 return VisitTypedefNameDecl(D, /*IsTypeAlias=*/true);
192}
193
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000194/// \brief Instantiate an initializer, breaking it into separate
195/// initialization arguments.
196///
197/// \param S The semantic analysis object.
198///
199/// \param Init The initializer to instantiate.
200///
201/// \param TemplateArgs Template arguments to be substituted into the
202/// initializer.
203///
204/// \param NewArgs Will be filled in with the instantiation arguments.
205///
206/// \returns true if an error occurred, false otherwise
207static bool InstantiateInitializer(Sema &S, Expr *Init,
208 const MultiLevelTemplateArgumentList &TemplateArgs,
209 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000210 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000211 SourceLocation &RParenLoc) {
212 NewArgs.clear();
213 LParenLoc = SourceLocation();
214 RParenLoc = SourceLocation();
215
216 if (!Init)
217 return false;
218
John McCall4765fa02010-12-06 08:20:24 +0000219 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000220 Init = ExprTemp->getSubExpr();
221
222 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
223 Init = Binder->getSubExpr();
224
225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
226 Init = ICE->getSubExprAsWritten();
227
228 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
229 LParenLoc = ParenList->getLParenLoc();
230 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000231 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
232 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000233 }
234
235 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000236 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000237 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
238 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000239 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000240
Douglas Gregor28329e52010-03-24 21:22:47 +0000241 // FIXME: Fake locations!
242 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000243 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000244 return false;
245 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000246 }
247
John McCall60d7b3a2010-08-24 06:29:42 +0000248 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000249 if (Result.isInvalid())
250 return true;
251
252 NewArgs.push_back(Result.takeAs<Expr>());
253 return false;
254}
255
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000256Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000257 // If this is the variable for an anonymous struct or union,
258 // instantiate the anonymous struct/union type first.
259 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
260 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
261 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
262 return 0;
263
John McCallce3ff2b2009-08-25 22:02:44 +0000264 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000265 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000266 TemplateArgs,
267 D->getTypeSpecStartLoc(),
268 D->getDeclName());
269 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000270 return 0;
271
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000272 if (DI->getType()->isFunctionType()) {
273 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
274 << D->isStaticDataMember() << DI->getType();
275 return 0;
276 }
277
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000278 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000279 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000280 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000281 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000282 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000283 D->getStorageClass(),
284 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000285 Var->setThreadSpecified(D->isThreadSpecified());
286 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000287 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000288
John McCallb6217662010-03-15 10:12:16 +0000289 // Substitute the nested name specifier, if any.
290 if (SubstQualifier(D, Var))
291 return 0;
292
Mike Stump1eb44332009-09-09 15:08:12 +0000293 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000294 // out-of-line, the instantiation will have the same lexical
295 // context (which will be a namespace scope) as the template.
296 if (D->isOutOfLine())
297 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000298
John McCall46460a62010-01-20 21:53:11 +0000299 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000300
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000301 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000302 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000303 Var->setReferenced(D->isReferenced());
304 }
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000305
Mike Stump390b4cc2009-05-16 07:39:55 +0000306 // FIXME: In theory, we could have a previous declaration for variables that
307 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000308 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000309 // FIXME: having to fake up a LookupResult is dumb.
310 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000311 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000312 if (D->isStaticDataMember())
313 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000314 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Douglas Gregor7caa6822009-07-24 20:34:43 +0000316 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000317 if (!D->isStaticDataMember())
318 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000319 Owner->makeDeclVisibleInContext(Var);
320 } else {
321 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000322 if (Owner->isFunctionOrMethod())
323 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000324 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000325 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000326
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000327 // Link instantiations of static data members back to the template from
328 // which they were instantiated.
329 if (Var->isStaticDataMember())
330 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000331 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000332
Douglas Gregor60c93c92010-02-09 07:26:29 +0000333 if (Var->getAnyInitializer()) {
334 // We already have an initializer in the class.
335 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000336 if (Var->isStaticDataMember() && !D->isOutOfLine())
337 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
338 else
339 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
340
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 // Instantiate the initializer.
342 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000343 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000344 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000345 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000346 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000347 // Attach the initializer to the declaration, if we have one.
348 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000349 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000350 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000351 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000352 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000354 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000355 RParenLoc,
356 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000357 } else {
358 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000359 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000360 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000361 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000362 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000363 // FIXME: Not too happy about invalidating the declaration
364 // because of a bogus initializer.
365 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000366 }
367
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000368 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000369 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
370 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000371 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000372
Douglas Gregor5764f612010-05-08 23:05:03 +0000373 // Diagnose unused local variables.
374 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
375 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000376
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000377 return Var;
378}
379
Abramo Bagnara6206d532010-06-05 05:09:32 +0000380Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
381 AccessSpecDecl* AD
382 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
383 D->getAccessSpecifierLoc(), D->getColonLoc());
384 Owner->addHiddenDecl(AD);
385 return AD;
386}
387
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000388Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
389 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000390 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000391 if (DI->getType()->isDependentType() ||
392 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000393 DI = SemaRef.SubstType(DI, TemplateArgs,
394 D->getLocation(), D->getDeclName());
395 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000396 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000397 Invalid = true;
398 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000399 // C++ [temp.arg.type]p3:
400 // If a declaration acquires a function type through a type
401 // dependent on a template-parameter and this causes a
402 // declaration that does not use the syntactic form of a
403 // function declarator to have function type, the program is
404 // ill-formed.
405 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000406 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407 Invalid = true;
408 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000409 } else {
410 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000411 }
412
413 Expr *BitWidth = D->getBitWidth();
414 if (Invalid)
415 BitWidth = 0;
416 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000417 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000418 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
John McCall60d7b3a2010-08-24 06:29:42 +0000420 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000421 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422 if (InstantiatedBitWidth.isInvalid()) {
423 Invalid = true;
424 BitWidth = 0;
425 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000426 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 }
428
John McCall07fb6be2009-10-22 23:33:21 +0000429 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
430 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000431 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000432 D->getLocation(),
433 D->isMutable(),
434 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000435 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000436 D->getAccess(),
437 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000438 if (!Field) {
439 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000440 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
John McCall1d8d1cc2010-08-01 02:01:53 +0000443 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000444
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000445 if (Invalid)
446 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000448 if (!Field->getDeclName()) {
449 // Keep track of where this decl came from.
450 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000451 }
452 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
453 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000454 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000455 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000459 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000460 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000461
462 return Field;
463}
464
Francois Pichet87c2e122010-11-21 06:08:52 +0000465Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
466 NamedDecl **NamedChain =
467 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
468
469 int i = 0;
470 for (IndirectFieldDecl::chain_iterator PI =
471 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000472 PI != PE; ++PI) {
473 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
474 TemplateArgs);
475 if (!Next)
476 return 0;
477
478 NamedChain[i++] = Next;
479 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000480
Francois Pichet40e17752010-12-09 10:07:54 +0000481 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000482 IndirectFieldDecl* IndirectField
483 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000484 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000485 NamedChain, D->getChainingSize());
486
487
488 IndirectField->setImplicit(D->isImplicit());
489 IndirectField->setAccess(D->getAccess());
490 Owner->addDecl(IndirectField);
491 return IndirectField;
492}
493
John McCall02cace72009-08-28 07:59:38 +0000494Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000495 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000496 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000497 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000498 TypeSourceInfo *InstTy;
499 // If this is an unsupported friend, don't bother substituting template
500 // arguments into it. The actual type referred to won't be used by any
501 // parts of Clang, and may not be valid for instantiating. Just use the
502 // same info for the instantiated friend.
503 if (D->isUnsupportedFriend()) {
504 InstTy = Ty;
505 } else {
506 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
507 D->getLocation(), DeclarationName());
508 }
509 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000510 return 0;
John McCall02cace72009-08-28 07:59:38 +0000511
Douglas Gregor06245bf2010-04-07 17:57:12 +0000512 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
513 if (!FD)
514 return 0;
515
516 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000517 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000518 Owner->addDecl(FD);
519 return FD;
520 }
521
522 NamedDecl *ND = D->getFriendDecl();
523 assert(ND && "friend decl must be a decl or a type!");
524
John McCallaf2094e2010-04-08 09:05:18 +0000525 // All of the Visit implementations for the various potential friend
526 // declarations have to be carefully written to work for friend
527 // objects, with the most important detail being that the target
528 // decl should almost certainly not be placed in Owner.
529 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000530 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
John McCall02cace72009-08-28 07:59:38 +0000532 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000533 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
534 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000535 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000536 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000537 Owner->addDecl(FD);
538 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000539}
540
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000541Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
542 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Douglas Gregorac7610d2009-06-22 20:57:11 +0000544 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000545 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000546
John McCall60d7b3a2010-08-24 06:29:42 +0000547 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000548 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000549 if (InstantiatedAssertExpr.isInvalid())
550 return 0;
551
John McCall60d7b3a2010-08-24 06:29:42 +0000552 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000553 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000554 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000555 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000556 Message.get(),
557 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000558}
559
560Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000561 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000562 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000563 /*PrevDecl=*/0, D->isScoped(),
564 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000565 if (D->isFixed()) {
566 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
567 // If we have type source information for the underlying type, it means it
568 // has been explicitly set by the user. Perform substitution on it before
569 // moving on.
570 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
571 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
572 TemplateArgs,
573 UnderlyingLoc,
574 DeclarationName()));
575
576 if (!Enum->getIntegerTypeSourceInfo())
577 Enum->setIntegerType(SemaRef.Context.IntTy);
578 }
579 else {
580 assert(!D->getIntegerType()->isDependentType()
581 && "Dependent type without type source info");
582 Enum->setIntegerType(D->getIntegerType());
583 }
584 }
585
John McCall5b629aa2010-10-22 23:36:17 +0000586 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
587
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000588 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000589 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000590 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000591 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000592 Enum->startDefinition();
593
Douglas Gregor96084f12010-03-01 19:00:07 +0000594 if (D->getDeclContext()->isFunctionOrMethod())
595 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
596
John McCalld226f652010-08-21 09:40:31 +0000597 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000598
599 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000600 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
601 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602 EC != ECEnd; ++EC) {
603 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000604 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000605 if (Expr *UninstValue = EC->getInitExpr()) {
606 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000607 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000608 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000609
John McCallce3ff2b2009-08-25 22:02:44 +0000610 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000611 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000612
613 // Drop the initial value and continue.
614 bool isInvalid = false;
615 if (Value.isInvalid()) {
616 Value = SemaRef.Owned((Expr *)0);
617 isInvalid = true;
618 }
619
Mike Stump1eb44332009-09-09 15:08:12 +0000620 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000621 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
622 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000623 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000624
625 if (isInvalid) {
626 if (EnumConst)
627 EnumConst->setInvalidDecl();
628 Enum->setInvalidDecl();
629 }
630
631 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000632 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
633
John McCall3b85ecf2010-01-23 22:37:59 +0000634 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000635 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000636 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000637 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000638
639 if (D->getDeclContext()->isFunctionOrMethod()) {
640 // If the enumeration is within a function or method, record the enum
641 // constant as a local.
642 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
643 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000644 }
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000647 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000648 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000649 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000650 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000651 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000652 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000653
654 return Enum;
655}
656
Douglas Gregor6477b692009-03-25 15:04:13 +0000657Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
658 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
659 return 0;
660}
661
John McCalle29ba202009-08-20 01:44:21 +0000662Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000663 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
664
Douglas Gregor550d9b22009-10-31 17:21:17 +0000665 // Create a local instantiation scope for this class template, which
666 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000667 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000668 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000669 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000670 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000671 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000672
673 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000674
675 // Instantiate the qualifier. We have to do this first in case
676 // we're a friend declaration, because if we are then we need to put
677 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000678 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
679 if (QualifierLoc) {
680 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
681 TemplateArgs);
682 if (!QualifierLoc)
683 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000684 }
685
686 CXXRecordDecl *PrevDecl = 0;
687 ClassTemplateDecl *PrevClassTemplate = 0;
688
Nick Lewycky37574f52010-11-08 23:29:42 +0000689 if (!isFriend && Pattern->getPreviousDeclaration()) {
690 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
691 if (Found.first != Found.second) {
692 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
693 if (PrevClassTemplate)
694 PrevDecl = PrevClassTemplate->getTemplatedDecl();
695 }
696 }
697
John McCall93ba8572010-03-25 06:39:04 +0000698 // If this isn't a friend, then it's a member template, in which
699 // case we just want to build the instantiation in the
700 // specialization. If it is a friend, we want to build it in
701 // the appropriate context.
702 DeclContext *DC = Owner;
703 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000704 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000705 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000706 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000707 DC = SemaRef.computeDeclContext(SS);
708 if (!DC) return 0;
709 } else {
710 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
711 Pattern->getDeclContext(),
712 TemplateArgs);
713 }
714
715 // Look for a previous declaration of the template in the owning
716 // context.
717 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
718 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
719 SemaRef.LookupQualifiedName(R, DC);
720
721 if (R.isSingleResult()) {
722 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
723 if (PrevClassTemplate)
724 PrevDecl = PrevClassTemplate->getTemplatedDecl();
725 }
726
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000727 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000728 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000729 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000730 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000731 return 0;
732 }
733
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000734 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000735 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000736 bool Complain = true;
737
738 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
739 // template for struct std::tr1::__detail::_Map_base, where the
740 // template parameters of the friend declaration don't match the
741 // template parameters of the original declaration. In this one
742 // case, we don't complain about the ill-formed friend
743 // declaration.
744 if (isFriend && Pattern->getIdentifier() &&
745 Pattern->getIdentifier()->isStr("_Map_base") &&
746 DC->isNamespace() &&
747 cast<NamespaceDecl>(DC)->getIdentifier() &&
748 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
749 DeclContext *DCParent = DC->getParent();
750 if (DCParent->isNamespace() &&
751 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
752 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
753 DeclContext *DCParent2 = DCParent->getParent();
754 if (DCParent2->isNamespace() &&
755 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
756 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
757 DCParent2->getParent()->isTranslationUnit())
758 Complain = false;
759 }
760 }
761
John McCall93ba8572010-03-25 06:39:04 +0000762 TemplateParameterList *PrevParams
763 = PrevClassTemplate->getTemplateParameters();
764
765 // Make sure the parameter lists match.
766 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000767 Complain,
768 Sema::TPL_TemplateMatch)) {
769 if (Complain)
770 return 0;
771
772 AdoptedPreviousTemplateParams = true;
773 InstParams = PrevParams;
774 }
John McCall93ba8572010-03-25 06:39:04 +0000775
776 // Do some additional validation, then merge default arguments
777 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000778 if (!AdoptedPreviousTemplateParams &&
779 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000780 Sema::TPC_ClassTemplate))
781 return 0;
782 }
783 }
784
John McCalle29ba202009-08-20 01:44:21 +0000785 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000786 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000787 Pattern->getLocStart(), Pattern->getLocation(),
788 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000789 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000790
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000791 if (QualifierLoc)
792 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000793
John McCalle29ba202009-08-20 01:44:21 +0000794 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000795 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
796 D->getIdentifier(), InstParams, RecordInst,
797 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000798 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000799
John McCall93ba8572010-03-25 06:39:04 +0000800 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000801 if (PrevClassTemplate)
802 Inst->setAccess(PrevClassTemplate->getAccess());
803 else
804 Inst->setAccess(D->getAccess());
805
John McCall93ba8572010-03-25 06:39:04 +0000806 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
807 // TODO: do we want to track the instantiation progeny of this
808 // friend target decl?
809 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000810 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000811 if (!PrevClassTemplate)
812 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000813 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000814
815 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000816 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000817 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000818
Douglas Gregor259571e2009-10-30 22:42:42 +0000819 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000820 if (isFriend) {
821 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000822 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000823 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000824
John McCalle29ba202009-08-20 01:44:21 +0000825 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000826
827 if (!PrevClassTemplate) {
828 // Queue up any out-of-line partial specializations of this member
829 // class template; the client will force their instantiation once
830 // the enclosing class has been instantiated.
831 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
832 D->getPartialSpecializations(PartialSpecs);
833 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
834 if (PartialSpecs[I]->isOutOfLine())
835 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
836 }
837
John McCalle29ba202009-08-20 01:44:21 +0000838 return Inst;
839}
840
Douglas Gregord60e1052009-08-27 16:57:43 +0000841Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000842TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
843 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000844 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
845
846 // Lookup the already-instantiated declaration in the instantiation
847 // of the class template and return that.
848 DeclContext::lookup_result Found
849 = Owner->lookup(ClassTemplate->getDeclName());
850 if (Found.first == Found.second)
851 return 0;
852
853 ClassTemplateDecl *InstClassTemplate
854 = dyn_cast<ClassTemplateDecl>(*Found.first);
855 if (!InstClassTemplate)
856 return 0;
857
Douglas Gregord65587f2010-11-10 19:44:59 +0000858 if (ClassTemplatePartialSpecializationDecl *Result
859 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
860 return Result;
861
862 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000863}
864
865Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000866TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000867 // Create a local instantiation scope for this function template, which
868 // will contain the instantiations of the template parameters and then get
869 // merged with the local instantiation scope for the function template
870 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000871 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000872
Douglas Gregord60e1052009-08-27 16:57:43 +0000873 TemplateParameterList *TempParams = D->getTemplateParameters();
874 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000875 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000876 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000877
Douglas Gregora735b202009-10-13 14:39:41 +0000878 FunctionDecl *Instantiated = 0;
879 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
880 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
881 InstParams));
882 else
883 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
884 D->getTemplatedDecl(),
885 InstParams));
886
887 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000888 return 0;
889
John McCall46460a62010-01-20 21:53:11 +0000890 Instantiated->setAccess(D->getAccess());
891
Mike Stump1eb44332009-09-09 15:08:12 +0000892 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000893 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000894 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000895 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000896 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000897 assert(InstTemplate &&
898 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000899
John McCallb1a56e72010-03-26 23:10:15 +0000900 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
901
John McCalle976ffe2009-12-14 23:19:40 +0000902 // Link the instantiation back to the pattern *unless* this is a
903 // non-definition friend declaration.
904 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000905 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000906 InstTemplate->setInstantiatedFromMemberTemplate(D);
907
John McCallb1a56e72010-03-26 23:10:15 +0000908 // Make declarations visible in the appropriate context.
909 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000910 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000911
Douglas Gregord60e1052009-08-27 16:57:43 +0000912 return InstTemplate;
913}
914
Douglas Gregord475b8d2009-03-25 21:17:03 +0000915Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
916 CXXRecordDecl *PrevDecl = 0;
917 if (D->isInjectedClassName())
918 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000919 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000920 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
921 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000922 TemplateArgs);
923 if (!Prev) return 0;
924 PrevDecl = cast<CXXRecordDecl>(Prev);
925 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926
927 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000928 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000929 D->getLocStart(), D->getLocation(),
930 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000931
932 // Substitute the nested name specifier, if any.
933 if (SubstQualifier(D, Record))
934 return 0;
935
Douglas Gregord475b8d2009-03-25 21:17:03 +0000936 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000937 // FIXME: Check against AS_none is an ugly hack to work around the issue that
938 // the tag decls introduced by friend class declarations don't have an access
939 // specifier. Remove once this area of the code gets sorted out.
940 if (D->getAccess() != AS_none)
941 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000942 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000943 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000944
John McCall02cace72009-08-28 07:59:38 +0000945 // If the original function was part of a friend declaration,
946 // inherit its namespace state.
947 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
948 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
949
Douglas Gregor9901c572010-05-21 00:31:19 +0000950 // Make sure that anonymous structs and unions are recorded.
951 if (D->isAnonymousStructOrUnion()) {
952 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000953 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000954 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
955 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000956
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000957 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000958 return Record;
959}
960
John McCall02cace72009-08-28 07:59:38 +0000961/// Normal class members are of more specific types and therefore
962/// don't make it here. This function serves two purposes:
963/// 1) instantiating function templates
964/// 2) substituting friend declarations
965/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000966Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000967 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000968 // Check whether there is already a function template specialization for
969 // this declaration.
970 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
971 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000972 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000973 std::pair<const TemplateArgument *, unsigned> Innermost
974 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000976 FunctionDecl *SpecFunc
977 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
978 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor127102b2009-06-29 20:59:39 +0000980 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000981 if (SpecFunc)
982 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
John McCallb0cb0222010-03-27 05:57:59 +0000985 bool isFriend;
986 if (FunctionTemplate)
987 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
988 else
989 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
990
Douglas Gregor79c22782010-01-16 20:21:20 +0000991 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000992 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000993 !(isa<Decl>(Owner) &&
994 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000995 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregore53060f2009-06-25 22:08:12 +0000997 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000998 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
999 TInfo = SubstFunctionType(D, Params);
1000 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001001 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001002 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001003
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001004 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1005 if (QualifierLoc) {
1006 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1007 TemplateArgs);
1008 if (!QualifierLoc)
1009 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001010 }
1011
John McCall68b6b872010-02-06 01:50:47 +00001012 // If we're instantiating a local function declaration, put the result
1013 // in the owner; otherwise we need to find the instantiated context.
1014 DeclContext *DC;
1015 if (D->getDeclContext()->isFunctionOrMethod())
1016 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001017 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001018 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001019 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001020 DC = SemaRef.computeDeclContext(SS);
1021 if (!DC) return 0;
1022 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001023 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1024 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001025 }
John McCall68b6b872010-02-06 01:50:47 +00001026
John McCall02cace72009-08-28 07:59:38 +00001027 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001028 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1029 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001030 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001031 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001032
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001033 if (QualifierLoc)
1034 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001035
John McCallb1a56e72010-03-26 23:10:15 +00001036 DeclContext *LexicalDC = Owner;
1037 if (!isFriend && D->isOutOfLine()) {
1038 assert(D->getDeclContext()->isFileContext());
1039 LexicalDC = D->getDeclContext();
1040 }
1041
1042 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Douglas Gregore53060f2009-06-25 22:08:12 +00001044 // Attach the parameters
1045 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001046 if (Params[P])
1047 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001048 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001049
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001050 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001051 if (TemplateParams) {
1052 // Our resulting instantiation is actually a function template, since we
1053 // are substituting only the outer template parameters. For example, given
1054 //
1055 // template<typename T>
1056 // struct X {
1057 // template<typename U> friend void f(T, U);
1058 // };
1059 //
1060 // X<int> x;
1061 //
1062 // We are instantiating the friend function template "f" within X<int>,
1063 // which means substituting int for T, but leaving "f" as a friend function
1064 // template.
1065 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001066 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001067 Function->getLocation(),
1068 Function->getDeclName(),
1069 TemplateParams, Function);
1070 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001071
1072 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001073
1074 if (isFriend && D->isThisDeclarationADefinition()) {
1075 // TODO: should we remember this connection regardless of whether
1076 // the friend declaration provided a body?
1077 FunctionTemplate->setInstantiatedFromMemberTemplate(
1078 D->getDescribedFunctionTemplate());
1079 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001080 } else if (FunctionTemplate) {
1081 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001082 std::pair<const TemplateArgument *, unsigned> Innermost
1083 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001084 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001085 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001086 Innermost.first,
1087 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001088 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001089 } else if (isFriend && D->isThisDeclarationADefinition()) {
1090 // TODO: should we remember this connection regardless of whether
1091 // the friend declaration provided a body?
1092 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001093 }
Douglas Gregora735b202009-10-13 14:39:41 +00001094
Douglas Gregore53060f2009-06-25 22:08:12 +00001095 if (InitFunctionInstantiation(Function, D))
1096 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregore53060f2009-06-25 22:08:12 +00001098 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001099 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001100
John McCall68263142009-11-18 22:49:29 +00001101 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1102 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1103
John McCallaf2094e2010-04-08 09:05:18 +00001104 if (DependentFunctionTemplateSpecializationInfo *Info
1105 = D->getDependentSpecializationInfo()) {
1106 assert(isFriend && "non-friend has dependent specialization info?");
1107
1108 // This needs to be set now for future sanity.
1109 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1110
1111 // Instantiate the explicit template arguments.
1112 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1113 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001114 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1115 ExplicitArgs, TemplateArgs))
1116 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001117
1118 // Map the candidate templates to their instantiations.
1119 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1120 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1121 Info->getTemplate(I),
1122 TemplateArgs);
1123 if (!Temp) return 0;
1124
1125 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1126 }
1127
1128 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1129 &ExplicitArgs,
1130 Previous))
1131 Function->setInvalidDecl();
1132
1133 isExplicitSpecialization = true;
1134
1135 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001136 // Look only into the namespace where the friend would be declared to
1137 // find a previous declaration. This is the innermost enclosing namespace,
1138 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001139 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001140
Douglas Gregora735b202009-10-13 14:39:41 +00001141 // In C++, the previous declaration we find might be a tag type
1142 // (class or enum). In this case, the new declaration will hide the
1143 // tag type. Note that this does does not apply if we're declaring a
1144 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001145 if (Previous.isSingleTagDecl())
1146 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001147 }
1148
John McCall9f54ad42009-12-10 09:41:52 +00001149 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001150 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001151
John McCall76d32642010-04-24 01:30:58 +00001152 NamedDecl *PrincipalDecl = (TemplateParams
1153 ? cast<NamedDecl>(FunctionTemplate)
1154 : Function);
1155
Douglas Gregora735b202009-10-13 14:39:41 +00001156 // If the original function was part of a friend declaration,
1157 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001158 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001159 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001160 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001161 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001162 else
Douglas Gregora735b202009-10-13 14:39:41 +00001163 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001164
1165 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1166 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001167
Gabor Greif77535df2010-08-30 22:25:56 +00001168 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001169
Douglas Gregor238058c2010-05-18 05:45:02 +00001170 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1171 D->isThisDeclarationADefinition()) {
1172 // Check for a function body.
1173 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001174 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001175 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1176 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1177 << Function->getDeclName();
1178 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1179 Function->setInvalidDecl();
1180 }
1181 // Check for redefinitions due to other instantiations of this or
1182 // a similar friend function.
1183 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1184 REnd = Function->redecls_end();
1185 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001186 if (*R == Function)
1187 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001188 switch (R->getFriendObjectKind()) {
1189 case Decl::FOK_None:
1190 if (!queuedInstantiation && R->isUsed(false)) {
1191 if (MemberSpecializationInfo *MSInfo
1192 = Function->getMemberSpecializationInfo()) {
1193 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1194 SourceLocation Loc = R->getLocation(); // FIXME
1195 MSInfo->setPointOfInstantiation(Loc);
1196 SemaRef.PendingLocalImplicitInstantiations.push_back(
1197 std::make_pair(Function, Loc));
1198 queuedInstantiation = true;
1199 }
1200 }
1201 }
1202 break;
1203 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001204 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001205 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001206 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001207 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1208 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001209 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001210 Function->setInvalidDecl();
1211 break;
1212 }
1213 }
1214 }
1215 }
Douglas Gregora735b202009-10-13 14:39:41 +00001216 }
1217
John McCall76d32642010-04-24 01:30:58 +00001218 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1219 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1220 PrincipalDecl->setNonMemberOperator();
1221
Douglas Gregore53060f2009-06-25 22:08:12 +00001222 return Function;
1223}
1224
Douglas Gregord60e1052009-08-27 16:57:43 +00001225Decl *
1226TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1227 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001228 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1229 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001230 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001231 // We are creating a function template specialization from a function
1232 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001233 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001234 std::pair<const TemplateArgument *, unsigned> Innermost
1235 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001237 FunctionDecl *SpecFunc
1238 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1239 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Douglas Gregor6b906862009-08-21 00:16:32 +00001241 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001242 if (SpecFunc)
1243 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001244 }
1245
John McCallb0cb0222010-03-27 05:57:59 +00001246 bool isFriend;
1247 if (FunctionTemplate)
1248 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1249 else
1250 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1251
Douglas Gregor79c22782010-01-16 20:21:20 +00001252 bool MergeWithParentScope = (TemplateParams != 0) ||
1253 !(isa<Decl>(Owner) &&
1254 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001255 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001256
John McCall4eab39f2010-10-19 02:26:41 +00001257 // Instantiate enclosing template arguments for friends.
1258 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1259 unsigned NumTempParamLists = 0;
1260 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1261 TempParamLists.set_size(NumTempParamLists);
1262 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1263 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1264 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1265 if (!InstParams)
1266 return NULL;
1267 TempParamLists[I] = InstParams;
1268 }
1269 }
1270
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001271 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001272 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1273 TInfo = SubstFunctionType(D, Params);
1274 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001275 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001276 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001277
Abramo Bagnara723df242010-12-14 22:11:44 +00001278 // \brief If the type of this function, after ignoring parentheses,
1279 // is not *directly* a function type, then we're instantiating a function
1280 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001281 //
1282 // typedef int functype(int, int);
1283 // functype func;
1284 //
1285 // In this case, we'll just go instantiate the ParmVarDecls that we
1286 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001287 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001288 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001289 llvm::SmallVector<QualType, 4> ParamTypes;
1290 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1291 D->getNumParams(), TemplateArgs, ParamTypes,
1292 &Params))
1293 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001294 }
1295
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001296 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1297 if (QualifierLoc) {
1298 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001299 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001300 if (!QualifierLoc)
1301 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001302 }
1303
1304 DeclContext *DC = Owner;
1305 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001306 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001307 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001308 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001309 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001310
1311 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1312 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001313 } else {
1314 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1315 D->getDeclContext(),
1316 TemplateArgs);
1317 }
1318 if (!DC) return 0;
1319 }
1320
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001321 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001322 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001323 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001325 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001326 DeclarationNameInfo NameInfo
1327 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001328 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001329 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001330 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001331 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001332 Constructor->isInlineSpecified(),
Sean Huntad7ec122011-05-05 03:36:28 +00001333 false,
1334 Constructor->isExplicitlyDefaulted());
Douglas Gregor17e32f32009-08-21 22:43:28 +00001335 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001336 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001337 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001338 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001339 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001340 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001341 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001342 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001343 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001344 Conversion->isExplicit(),
1345 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001346 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001347 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001348 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001349 D->isStatic(),
1350 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001351 D->isInlineSpecified(),
1352 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001353 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001354
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001355 if (QualifierLoc)
1356 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001357
Douglas Gregord60e1052009-08-27 16:57:43 +00001358 if (TemplateParams) {
1359 // Our resulting instantiation is actually a function template, since we
1360 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001361 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001362 // template<typename T>
1363 // struct X {
1364 // template<typename U> void f(T, U);
1365 // };
1366 //
1367 // X<int> x;
1368 //
1369 // We are instantiating the member template "f" within X<int>, which means
1370 // substituting int for T, but leaving "f" as a member function template.
1371 // Build the function template itself.
1372 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1373 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001374 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001375 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001376 if (isFriend) {
1377 FunctionTemplate->setLexicalDeclContext(Owner);
1378 FunctionTemplate->setObjectOfFriendDecl(true);
1379 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001380 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001381 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001382 } else if (FunctionTemplate) {
1383 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001384 std::pair<const TemplateArgument *, unsigned> Innermost
1385 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001386 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001387 TemplateArgumentList::CreateCopy(SemaRef.Context,
1388 Innermost.first,
1389 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001390 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001391 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001392 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001393 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001394 }
1395
Mike Stump1eb44332009-09-09 15:08:12 +00001396 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001397 // out-of-line, the instantiation will have the same lexical
1398 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001399 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001400 if (NumTempParamLists)
1401 Method->setTemplateParameterListsInfo(SemaRef.Context,
1402 NumTempParamLists,
1403 TempParamLists.data());
1404
John McCallb0cb0222010-03-27 05:57:59 +00001405 Method->setLexicalDeclContext(Owner);
1406 Method->setObjectOfFriendDecl(true);
1407 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001408 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregor5545e162009-03-24 00:38:23 +00001410 // Attach the parameters
1411 for (unsigned P = 0; P < Params.size(); ++P)
1412 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001413 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001414
1415 if (InitMethodInstantiation(Method, D))
1416 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001417
Abramo Bagnara25777432010-08-11 22:01:17 +00001418 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1419 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
John McCallb0cb0222010-03-27 05:57:59 +00001421 if (!FunctionTemplate || TemplateParams || isFriend) {
1422 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Douglas Gregordec06662009-08-21 18:42:58 +00001424 // In C++, the previous declaration we find might be a tag type
1425 // (class or enum). In this case, the new declaration will hide the
1426 // tag type. Note that this does does not apply if we're declaring a
1427 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001428 if (Previous.isSingleTagDecl())
1429 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001430 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001431
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001432 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001433 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001434
Douglas Gregor4ba31362009-12-01 17:24:26 +00001435 if (D->isPure())
1436 SemaRef.CheckPureMethod(Method, SourceRange());
1437
John McCall46460a62010-01-20 21:53:11 +00001438 Method->setAccess(D->getAccess());
1439
Anders Carlsson9eefa222011-01-20 06:52:44 +00001440 SemaRef.CheckOverrideControl(Method);
1441
John McCallb0cb0222010-03-27 05:57:59 +00001442 if (FunctionTemplate) {
1443 // If there's a function template, let our caller handle it.
1444 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1445 // Don't hide a (potentially) valid declaration with an invalid one.
1446 } else {
1447 NamedDecl *DeclToAdd = (TemplateParams
1448 ? cast<NamedDecl>(FunctionTemplate)
1449 : Method);
1450 if (isFriend)
1451 Record->makeDeclVisibleInContext(DeclToAdd);
1452 else
1453 Owner->addDecl(DeclToAdd);
1454 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001455
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001456 return Method;
1457}
1458
Douglas Gregor615c5d42009-03-24 16:43:20 +00001459Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001460 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001461}
1462
Douglas Gregor03b2b072009-03-24 00:15:49 +00001463Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001464 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001465}
1466
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001467Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001468 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001469}
1470
Douglas Gregor6477b692009-03-25 15:04:13 +00001471ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001472 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1473 llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001474}
1475
John McCalle29ba202009-08-20 01:44:21 +00001476Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1477 TemplateTypeParmDecl *D) {
1478 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001479 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001480
John McCalle29ba202009-08-20 01:44:21 +00001481 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001482 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1483 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001484 D->getDepth() - TemplateArgs.getNumLevels(),
1485 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001486 D->wasDeclaredWithTypename(),
1487 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001488 Inst->setAccess(AS_public);
1489
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001490 if (D->hasDefaultArgument())
1491 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001492
Douglas Gregor550d9b22009-10-31 17:21:17 +00001493 // Introduce this template parameter's instantiation into the instantiation
1494 // scope.
1495 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1496
John McCalle29ba202009-08-20 01:44:21 +00001497 return Inst;
1498}
1499
Douglas Gregor33642df2009-10-23 23:25:44 +00001500Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1501 NonTypeTemplateParmDecl *D) {
1502 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001503 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1504 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1505 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1506 bool IsExpandedParameterPack = false;
1507 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001508 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001509 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001510
1511 if (D->isExpandedParameterPack()) {
1512 // The non-type template parameter pack is an already-expanded pack
1513 // expansion of types. Substitute into each of the expanded types.
1514 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1515 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1516 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1517 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1518 TemplateArgs,
1519 D->getLocation(),
1520 D->getDeclName());
1521 if (!NewDI)
1522 return 0;
1523
1524 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1525 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1526 D->getLocation());
1527 if (NewT.isNull())
1528 return 0;
1529 ExpandedParameterPackTypes.push_back(NewT);
1530 }
1531
1532 IsExpandedParameterPack = true;
1533 DI = D->getTypeSourceInfo();
1534 T = DI->getType();
1535 } else if (isa<PackExpansionTypeLoc>(TL)) {
1536 // The non-type template parameter pack's type is a pack expansion of types.
1537 // Determine whether we need to expand this parameter pack into separate
1538 // types.
1539 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1540 TypeLoc Pattern = Expansion.getPatternLoc();
1541 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1542 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1543
1544 // Determine whether the set of unexpanded parameter packs can and should
1545 // be expanded.
1546 bool Expand = true;
1547 bool RetainExpansion = false;
1548 llvm::Optional<unsigned> OrigNumExpansions
1549 = Expansion.getTypePtr()->getNumExpansions();
1550 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1551 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1552 Pattern.getSourceRange(),
1553 Unexpanded.data(),
1554 Unexpanded.size(),
1555 TemplateArgs,
1556 Expand, RetainExpansion,
1557 NumExpansions))
1558 return 0;
1559
1560 if (Expand) {
1561 for (unsigned I = 0; I != *NumExpansions; ++I) {
1562 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1563 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1564 D->getLocation(),
1565 D->getDeclName());
1566 if (!NewDI)
1567 return 0;
1568
1569 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1570 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1571 NewDI->getType(),
1572 D->getLocation());
1573 if (NewT.isNull())
1574 return 0;
1575 ExpandedParameterPackTypes.push_back(NewT);
1576 }
1577
1578 // Note that we have an expanded parameter pack. The "type" of this
1579 // expanded parameter pack is the original expansion type, but callers
1580 // will end up using the expanded parameter pack types for type-checking.
1581 IsExpandedParameterPack = true;
1582 DI = D->getTypeSourceInfo();
1583 T = DI->getType();
1584 } else {
1585 // We cannot fully expand the pack expansion now, so substitute into the
1586 // pattern and create a new pack expansion type.
1587 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1588 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1589 D->getLocation(),
1590 D->getDeclName());
1591 if (!NewPattern)
1592 return 0;
1593
1594 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1595 NumExpansions);
1596 if (!DI)
1597 return 0;
1598
1599 T = DI->getType();
1600 }
1601 } else {
1602 // Simple case: substitution into a parameter that is not a parameter pack.
1603 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1604 D->getLocation(), D->getDeclName());
1605 if (!DI)
1606 return 0;
1607
1608 // Check that this type is acceptable for a non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001609 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1610 D->getLocation());
1611 if (T.isNull()) {
1612 T = SemaRef.Context.IntTy;
1613 Invalid = true;
1614 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001615 }
1616
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001617 NonTypeTemplateParmDecl *Param;
1618 if (IsExpandedParameterPack)
1619 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001620 D->getInnerLocStart(),
1621 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001622 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001623 D->getPosition(),
1624 D->getIdentifier(), T,
1625 DI,
1626 ExpandedParameterPackTypes.data(),
1627 ExpandedParameterPackTypes.size(),
1628 ExpandedParameterPackTypesAsWritten.data());
1629 else
1630 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001631 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001632 D->getLocation(),
1633 D->getDepth() - TemplateArgs.getNumLevels(),
1634 D->getPosition(),
1635 D->getIdentifier(), T,
1636 D->isParameterPack(), DI);
1637
Douglas Gregor9a299e02011-03-04 17:52:15 +00001638 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001639 if (Invalid)
1640 Param->setInvalidDecl();
1641
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001642 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001643
1644 // Introduce this template parameter's instantiation into the instantiation
1645 // scope.
1646 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001647 return Param;
1648}
1649
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001650Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001651TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1652 TemplateTemplateParmDecl *D) {
1653 // Instantiate the template parameter list of the template template parameter.
1654 TemplateParameterList *TempParams = D->getTemplateParameters();
1655 TemplateParameterList *InstParams;
1656 {
1657 // Perform the actual substitution of template parameters within a new,
1658 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001659 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001660 InstParams = SubstTemplateParams(TempParams);
1661 if (!InstParams)
1662 return NULL;
1663 }
1664
1665 // Build the template template parameter.
1666 TemplateTemplateParmDecl *Param
1667 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001668 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001669 D->getPosition(), D->isParameterPack(),
1670 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001671 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001672 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001673
Douglas Gregor9106ef72009-11-11 16:58:32 +00001674 // Introduce this template parameter's instantiation into the instantiation
1675 // scope.
1676 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1677
1678 return Param;
1679}
1680
Douglas Gregor48c32a72009-11-17 06:07:40 +00001681Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001682 // Using directives are never dependent (and never contain any types or
1683 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001684
1685 UsingDirectiveDecl *Inst
1686 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1687 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001688 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001689 D->getIdentLocation(),
1690 D->getNominatedNamespace(),
1691 D->getCommonAncestor());
1692 Owner->addDecl(Inst);
1693 return Inst;
1694}
1695
John McCalled976492009-12-04 22:46:56 +00001696Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001697
1698 // The nested name specifier may be dependent, for example
1699 // template <typename T> struct t {
1700 // struct s1 { T f1(); };
1701 // struct s2 : s1 { using s1::f1; };
1702 // };
1703 // template struct t<int>;
1704 // Here, in using s1::f1, s1 refers to t<T>::s1;
1705 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001706 NestedNameSpecifierLoc QualifierLoc
1707 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1708 TemplateArgs);
1709 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001710 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001711
1712 // The name info is non-dependent, so no transformation
1713 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001714 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001715
John McCall9f54ad42009-12-10 09:41:52 +00001716 // We only need to do redeclaration lookups if we're in a class
1717 // scope (in fact, it's not really even possible in non-class
1718 // scopes).
1719 bool CheckRedeclaration = Owner->isRecord();
1720
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001721 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1722 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001723
John McCalled976492009-12-04 22:46:56 +00001724 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001725 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001726 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001727 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001728 D->isTypeName());
1729
Douglas Gregor5149f372011-02-25 15:54:31 +00001730 CXXScopeSpec SS;
1731 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001732 if (CheckRedeclaration) {
1733 Prev.setHideTags(false);
1734 SemaRef.LookupQualifiedName(Prev, Owner);
1735
1736 // Check for invalid redeclarations.
1737 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1738 D->isTypeName(), SS,
1739 D->getLocation(), Prev))
1740 NewUD->setInvalidDecl();
1741
1742 }
1743
1744 if (!NewUD->isInvalidDecl() &&
1745 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001746 D->getLocation()))
1747 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001748
John McCalled976492009-12-04 22:46:56 +00001749 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1750 NewUD->setAccess(D->getAccess());
1751 Owner->addDecl(NewUD);
1752
John McCall9f54ad42009-12-10 09:41:52 +00001753 // Don't process the shadow decls for an invalid decl.
1754 if (NewUD->isInvalidDecl())
1755 return NewUD;
1756
John McCall323c3102009-12-22 22:26:37 +00001757 bool isFunctionScope = Owner->isFunctionOrMethod();
1758
John McCall9f54ad42009-12-10 09:41:52 +00001759 // Process the shadow decls.
1760 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1761 I != E; ++I) {
1762 UsingShadowDecl *Shadow = *I;
1763 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001764 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1765 Shadow->getLocation(),
1766 Shadow->getTargetDecl(),
1767 TemplateArgs));
1768 if (!InstTarget)
1769 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001770
1771 if (CheckRedeclaration &&
1772 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1773 continue;
1774
1775 UsingShadowDecl *InstShadow
1776 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1777 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001778
1779 if (isFunctionScope)
1780 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001781 }
John McCalled976492009-12-04 22:46:56 +00001782
1783 return NewUD;
1784}
1785
1786Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001787 // Ignore these; we handle them in bulk when processing the UsingDecl.
1788 return 0;
John McCalled976492009-12-04 22:46:56 +00001789}
1790
John McCall7ba107a2009-11-18 02:36:19 +00001791Decl * TemplateDeclInstantiator
1792 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001793 NestedNameSpecifierLoc QualifierLoc
1794 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1795 TemplateArgs);
1796 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001797 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001799 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001800 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001802 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1803 // Hence, no tranformation is required for it.
1804 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001805 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001806 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001807 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001808 /*instantiation*/ true,
1809 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001810 if (UD)
John McCalled976492009-12-04 22:46:56 +00001811 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1812
John McCall7ba107a2009-11-18 02:36:19 +00001813 return UD;
1814}
1815
1816Decl * TemplateDeclInstantiator
1817 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001818 NestedNameSpecifierLoc QualifierLoc
1819 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1820 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001821 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001822
John McCall7ba107a2009-11-18 02:36:19 +00001823 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001824 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001825
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001826 DeclarationNameInfo NameInfo
1827 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1828
John McCall7ba107a2009-11-18 02:36:19 +00001829 NamedDecl *UD =
1830 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001831 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001832 /*instantiation*/ true,
1833 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001834 if (UD)
John McCalled976492009-12-04 22:46:56 +00001835 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1836
Anders Carlsson0d8df782009-08-29 19:37:28 +00001837 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001838}
1839
John McCallce3ff2b2009-08-25 22:02:44 +00001840Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001841 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001842 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001843 if (D->isInvalidDecl())
1844 return 0;
1845
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001846 return Instantiator.Visit(D);
1847}
1848
John McCalle29ba202009-08-20 01:44:21 +00001849/// \brief Instantiates a nested template parameter list in the current
1850/// instantiation context.
1851///
1852/// \param L The parameter list to instantiate
1853///
1854/// \returns NULL if there was an error
1855TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001856TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001857 // Get errors for all the parameters before bailing out.
1858 bool Invalid = false;
1859
1860 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001861 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001862 ParamVector Params;
1863 Params.reserve(N);
1864 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1865 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001866 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001867 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001868 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001869 }
1870
1871 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001872 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001873 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001874
1875 TemplateParameterList *InstL
1876 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1877 L->getLAngleLoc(), &Params.front(), N,
1878 L->getRAngleLoc());
1879 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001880}
John McCalle29ba202009-08-20 01:44:21 +00001881
Douglas Gregored9c0f92009-10-29 00:04:11 +00001882/// \brief Instantiate the declaration of a class template partial
1883/// specialization.
1884///
1885/// \param ClassTemplate the (instantiated) class template that is partially
1886// specialized by the instantiation of \p PartialSpec.
1887///
1888/// \param PartialSpec the (uninstantiated) class template partial
1889/// specialization that we are instantiating.
1890///
Douglas Gregord65587f2010-11-10 19:44:59 +00001891/// \returns The instantiated partial specialization, if successful; otherwise,
1892/// NULL to indicate an error.
1893ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001894TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1895 ClassTemplateDecl *ClassTemplate,
1896 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001897 // Create a local instantiation scope for this class template partial
1898 // specialization, which will contain the instantiations of the template
1899 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001900 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001901
Douglas Gregored9c0f92009-10-29 00:04:11 +00001902 // Substitute into the template parameters of the class template partial
1903 // specialization.
1904 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1905 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1906 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001907 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001908
1909 // Substitute into the template arguments of the class template partial
1910 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001911 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001912 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1913 PartialSpec->getNumTemplateArgsAsWritten(),
1914 InstTemplateArgs, TemplateArgs))
1915 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001916
Douglas Gregored9c0f92009-10-29 00:04:11 +00001917 // Check that the template argument list is well-formed for this
1918 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001919 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001920 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1921 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001922 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001923 false,
1924 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001925 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001926
1927 // Figure out where to insert this class template partial specialization
1928 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001929 void *InsertPos = 0;
1930 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001931 = ClassTemplate->findPartialSpecialization(Converted.data(),
1932 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001933
1934 // Build the canonical type that describes the converted template
1935 // arguments of the class template partial specialization.
1936 QualType CanonType
1937 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001938 Converted.data(),
1939 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001940
1941 // Build the fully-sugared type for this class template
1942 // specialization as the user wrote in the specialization
1943 // itself. This means that we'll pretty-print the type retrieved
1944 // from the specialization's declaration the way that the user
1945 // actually wrote the specialization, rather than formatting the
1946 // name based on the "canonical" representation used to store the
1947 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001948 TypeSourceInfo *WrittenTy
1949 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1950 TemplateName(ClassTemplate),
1951 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001952 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001953 CanonType);
1954
1955 if (PrevDecl) {
1956 // We've already seen a partial specialization with the same template
1957 // parameters and template arguments. This can happen, for example, when
1958 // substituting the outer template arguments ends up causing two
1959 // class template partial specializations of a member class template
1960 // to have identical forms, e.g.,
1961 //
1962 // template<typename T, typename U>
1963 // struct Outer {
1964 // template<typename X, typename Y> struct Inner;
1965 // template<typename Y> struct Inner<T, Y>;
1966 // template<typename Y> struct Inner<U, Y>;
1967 // };
1968 //
1969 // Outer<int, int> outer; // error: the partial specializations of Inner
1970 // // have the same signature.
1971 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001972 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001973 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1974 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001975 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001976 }
1977
1978
1979 // Create the class template partial specialization declaration.
1980 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001981 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1982 PartialSpec->getTagKind(),
1983 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001984 PartialSpec->getLocStart(),
1985 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001986 InstParams,
1987 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001988 Converted.data(),
1989 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001990 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001991 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001992 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001993 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001994 // Substitute the nested name specifier, if any.
1995 if (SubstQualifier(PartialSpec, InstPartialSpec))
1996 return 0;
1997
Douglas Gregored9c0f92009-10-29 00:04:11 +00001998 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001999 InstPartialSpec->setTypeAsWritten(WrittenTy);
2000
Douglas Gregored9c0f92009-10-29 00:04:11 +00002001 // Add this partial specialization to the set of class template partial
2002 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002003 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00002004 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002005}
2006
John McCall21ef0fa2010-03-11 09:03:00 +00002007TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002008TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002009 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002010 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2011 assert(OldTInfo && "substituting function without type source info");
2012 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002013 TypeSourceInfo *NewTInfo
2014 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2015 D->getTypeSpecStartLoc(),
2016 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002017 if (!NewTInfo)
2018 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002019
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002020 if (NewTInfo != OldTInfo) {
2021 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002022 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002023 if (FunctionProtoTypeLoc *OldProtoLoc
2024 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002025 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002026 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2027 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002028 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2029 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2030 OldIdx != NumOldParams; ++OldIdx) {
2031 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2032 if (!OldParam->isParameterPack() ||
2033 (NewIdx < NumNewParams &&
2034 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2035 // Simple case: normal parameter, or a parameter pack that's
2036 // instantiated to a (still-dependent) parameter pack.
2037 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2038 Params.push_back(NewParam);
2039 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2040 NewParam);
2041 continue;
2042 }
2043
2044 // Parameter pack: make the instantiation an argument pack.
2045 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2046 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002047 unsigned NumArgumentsInExpansion
2048 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2049 TemplateArgs);
2050 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002051 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2052 Params.push_back(NewParam);
2053 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2054 NewParam);
2055 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002056 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002057 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002058 } else {
2059 // The function type itself was not dependent and therefore no
2060 // substitution occurred. However, we still need to instantiate
2061 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002062 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002063 if (FunctionProtoTypeLoc *OldProtoLoc
2064 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2065 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2066 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2067 if (!Parm)
2068 return 0;
2069 Params.push_back(Parm);
2070 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002071 }
2072 }
John McCall21ef0fa2010-03-11 09:03:00 +00002073 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002074}
2075
Mike Stump1eb44332009-09-09 15:08:12 +00002076/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002077/// declaration (New) from the corresponding fields of its template (Tmpl).
2078///
2079/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002080bool
2081TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002082 FunctionDecl *Tmpl) {
2083 if (Tmpl->isDeleted())
2084 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregorcca9e962009-07-01 22:01:06 +00002086 // If we are performing substituting explicitly-specified template arguments
2087 // or deduced template arguments into a function template and we reach this
2088 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002089 // to keeping the new function template specialization. We therefore
2090 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002091 // into a template instantiation for this specific function template
2092 // specialization, which is not a SFINAE context, so that we diagnose any
2093 // further errors in the declaration itself.
2094 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2095 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2096 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2097 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002098 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002099 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002100 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002101 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002102 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002103 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2104 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002105 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002106 }
2107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002109 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2110 assert(Proto && "Function template without prototype?");
2111
Sebastian Redl60618fa2011-03-12 11:50:43 +00002112 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002113 // The function has an exception specification or a "noreturn"
2114 // attribute. Substitute into each of the exception types.
2115 llvm::SmallVector<QualType, 4> Exceptions;
2116 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2117 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002118 if (const PackExpansionType *PackExpansion
2119 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2120 // We have a pack expansion. Instantiate it.
2121 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2122 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2123 Unexpanded);
2124 assert(!Unexpanded.empty() &&
2125 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002126
Douglas Gregorb99268b2010-12-21 00:52:54 +00002127 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002128 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002129 llvm::Optional<unsigned> NumExpansions
2130 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002131 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2132 SourceRange(),
2133 Unexpanded.data(),
2134 Unexpanded.size(),
2135 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002136 Expand,
2137 RetainExpansion,
2138 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002139 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002140
Douglas Gregorb99268b2010-12-21 00:52:54 +00002141 if (!Expand) {
2142 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002143 // just substitute into the pattern and create a new pack expansion
2144 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002145 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2146 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2147 TemplateArgs,
2148 New->getLocation(), New->getDeclName());
2149 if (T.isNull())
2150 break;
2151
Douglas Gregorcded4f62011-01-14 17:04:44 +00002152 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002153 Exceptions.push_back(T);
2154 continue;
2155 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002156
Douglas Gregorb99268b2010-12-21 00:52:54 +00002157 // Substitute into the pack expansion pattern for each template
2158 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002159 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002160 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2161
2162 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2163 TemplateArgs,
2164 New->getLocation(), New->getDeclName());
2165 if (T.isNull()) {
2166 Invalid = true;
2167 break;
2168 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002169
Douglas Gregorb99268b2010-12-21 00:52:54 +00002170 Exceptions.push_back(T);
2171 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002172
Douglas Gregorb99268b2010-12-21 00:52:54 +00002173 if (Invalid)
2174 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002175
Douglas Gregorb99268b2010-12-21 00:52:54 +00002176 continue;
2177 }
2178
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002179 QualType T
2180 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2181 New->getLocation(), New->getDeclName());
2182 if (T.isNull() ||
2183 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2184 continue;
2185
2186 Exceptions.push_back(T);
2187 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002188 Expr *NoexceptExpr = 0;
2189 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2190 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2191 if (E.isUsable())
2192 NoexceptExpr = E.take();
2193 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002194
2195 // Rebuild the function type
2196
John McCalle23cf432010-12-14 08:05:40 +00002197 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002198 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002199 EPI.NumExceptions = Exceptions.size();
2200 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002201 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002202 EPI.ExtInfo = Proto->getExtInfo();
2203
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002204 const FunctionProtoType *NewProto
2205 = New->getType()->getAs<FunctionProtoType>();
2206 assert(NewProto && "Template instantiation without function prototype?");
2207 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2208 NewProto->arg_type_begin(),
2209 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002210 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002211 }
2212
John McCall1d8d1cc2010-08-01 02:01:53 +00002213 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002214
Douglas Gregore53060f2009-06-25 22:08:12 +00002215 return false;
2216}
2217
Douglas Gregor5545e162009-03-24 00:38:23 +00002218/// \brief Initializes common fields of an instantiated method
2219/// declaration (New) from the corresponding fields of its template
2220/// (Tmpl).
2221///
2222/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002223bool
2224TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002225 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002226 if (InitFunctionInstantiation(New, Tmpl))
2227 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregor5545e162009-03-24 00:38:23 +00002229 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002230 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002231 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002232
2233 // FIXME: attributes
2234 // FIXME: New needs a pointer to Tmpl
2235 return false;
2236}
Douglas Gregora58861f2009-05-13 20:28:22 +00002237
2238/// \brief Instantiate the definition of the given function from its
2239/// template.
2240///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002241/// \param PointOfInstantiation the point at which the instantiation was
2242/// required. Note that this is not precisely a "point of instantiation"
2243/// for the function, but it's close.
2244///
Douglas Gregora58861f2009-05-13 20:28:22 +00002245/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002246/// function template specialization or member function of a class template
2247/// specialization.
2248///
2249/// \param Recursive if true, recursively instantiates any functions that
2250/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002251///
2252/// \param DefinitionRequired if true, then we are performing an explicit
2253/// instantiation where the body of the function is required. Complain if
2254/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002255void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002256 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002257 bool Recursive,
2258 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002259 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002260 return;
2261
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002262 // Never instantiate an explicit specialization.
2263 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2264 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002265
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002266 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002267 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002268 Stmt *Pattern = 0;
2269 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002270 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002271
Francois Pichet8387e2a2011-04-22 22:18:13 +00002272 // Postpone late parsed template instantiations.
2273 if (PatternDecl->isLateTemplateParsed() && !LateTemplateParser) {
2274 PendingInstantiations.push_back(
2275 std::make_pair(Function, PointOfInstantiation));
2276 return;
2277 }
2278
2279 // Call the LateTemplateParser callback if there a need to late parse
2280 // a templated function definition.
2281 if (!Pattern && PatternDecl && PatternDecl->isLateTemplateParsed() &&
2282 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002283 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002284 Pattern = PatternDecl->getBody(PatternDecl);
2285 }
2286
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002287 if (!Pattern) {
2288 if (DefinitionRequired) {
2289 if (Function->getPrimaryTemplate())
2290 Diag(PointOfInstantiation,
2291 diag::err_explicit_instantiation_undefined_func_template)
2292 << Function->getPrimaryTemplate();
2293 else
2294 Diag(PointOfInstantiation,
2295 diag::err_explicit_instantiation_undefined_member)
2296 << 1 << Function->getDeclName() << Function->getDeclContext();
2297
2298 if (PatternDecl)
2299 Diag(PatternDecl->getLocation(),
2300 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002301 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002302 } else if (Function->getTemplateSpecializationKind()
2303 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002304 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002305 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002306 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002307
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002308 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002309 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002310
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002311 // C++0x [temp.explicit]p9:
2312 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002313 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002314 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002315 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002316 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002317 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002318 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002320 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2321 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002322 return;
2323
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002324 // If we're performing recursive template instantiation, create our own
2325 // queue of pending implicit instantiations that we will instantiate later,
2326 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002327 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002328 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002329 if (Recursive) {
2330 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002331 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Douglas Gregor9679caf2010-05-12 17:27:19 +00002334 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002335 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002336 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002337
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002338 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002339 // recorded, unless we're actually a member function within a local
2340 // class, in which case we need to merge our results with the parent
2341 // scope (of the enclosing function).
2342 bool MergeWithParentScope = false;
2343 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2344 MergeWithParentScope = Rec->isLocalClass();
2345
2346 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002348 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002349 // instantiation scope, and set the parameter names to those used
2350 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002351 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002352 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2353 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002354 if (!PatternParam->isParameterPack()) {
2355 // Simple case: not a parameter pack.
2356 assert(FParamIdx < Function->getNumParams());
2357 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2358 FunctionParam->setDeclName(PatternParam->getDeclName());
2359 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2360 ++FParamIdx;
2361 continue;
2362 }
2363
2364 // Expand the parameter pack.
2365 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2366 for (unsigned NumFParams = Function->getNumParams();
2367 FParamIdx < NumFParams;
2368 ++FParamIdx) {
2369 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2370 FunctionParam->setDeclName(PatternParam->getDeclName());
2371 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2372 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002373 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002374
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002375 // Enter the scope of this instantiation. We don't use
2376 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002377 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002378
Mike Stump1eb44332009-09-09 15:08:12 +00002379 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002380 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002381
2382 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002383 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002384 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2385 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2386 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002387 }
2388
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002389 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002390 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002391
Douglas Gregor52604ab2009-09-11 21:19:12 +00002392 if (Body.isInvalid())
2393 Function->setInvalidDecl();
2394
John McCall9ae2f072010-08-23 23:25:46 +00002395 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002396 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002397
John McCall0c01d182010-03-24 05:22:00 +00002398 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2399
John McCalleee1d542011-02-14 07:13:47 +00002400 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002401
2402 DeclGroupRef DG(Function);
2403 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregor60406be2010-01-16 22:29:39 +00002405 // This class may have local implicit instantiations that need to be
2406 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002407 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002408 Scope.Exit();
2409
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002410 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002411 // Define any pending vtables.
2412 DefineUsedVTables();
2413
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002414 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002415 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002416 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002418 // Restore the set of pending vtables.
2419 VTableUses.swap(SavedVTableUses);
2420
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002421 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002422 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002423 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002424}
2425
2426/// \brief Instantiate the definition of the given variable from its
2427/// template.
2428///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002429/// \param PointOfInstantiation the point at which the instantiation was
2430/// required. Note that this is not precisely a "point of instantiation"
2431/// for the function, but it's close.
2432///
2433/// \param Var the already-instantiated declaration of a static member
2434/// variable of a class template specialization.
2435///
2436/// \param Recursive if true, recursively instantiates any functions that
2437/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002438///
2439/// \param DefinitionRequired if true, then we are performing an explicit
2440/// instantiation where an out-of-line definition of the member variable
2441/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002442void Sema::InstantiateStaticDataMemberDefinition(
2443 SourceLocation PointOfInstantiation,
2444 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002445 bool Recursive,
2446 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002447 if (Var->isInvalidDecl())
2448 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor7caa6822009-07-24 20:34:43 +00002450 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002451 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002452 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002453 assert(Def->isStaticDataMember() && "Not a static data member?");
2454 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Douglas Gregor0d035142009-10-27 18:42:08 +00002456 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002457 // We did not find an out-of-line definition of this static data member,
2458 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002459 // instantiate this definition (or provide a specialization for it) in
2460 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002461 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002462 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002463 Diag(PointOfInstantiation,
2464 diag::err_explicit_instantiation_undefined_member)
2465 << 2 << Var->getDeclName() << Var->getDeclContext();
2466 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002467 } else if (Var->getTemplateSpecializationKind()
2468 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002469 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002470 std::make_pair(Var, PointOfInstantiation));
2471 }
2472
Douglas Gregor7caa6822009-07-24 20:34:43 +00002473 return;
2474 }
2475
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002476 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002477 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002478 return;
2479
2480 // C++0x [temp.explicit]p9:
2481 // Except for inline functions, other explicit instantiation declarations
2482 // have the effect of suppressing the implicit instantiation of the entity
2483 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002484 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002485 == TSK_ExplicitInstantiationDeclaration)
2486 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Douglas Gregor7caa6822009-07-24 20:34:43 +00002488 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2489 if (Inst)
2490 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Douglas Gregor7caa6822009-07-24 20:34:43 +00002492 // If we're performing recursive template instantiation, create our own
2493 // queue of pending implicit instantiations that we will instantiate later,
2494 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002495 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002496 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002497 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregor7caa6822009-07-24 20:34:43 +00002499 // Enter the scope of this instantiation. We don't use
2500 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002501 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002502
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002503 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002504 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002505 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002506
2507 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002508
2509 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002510 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2511 assert(MSInfo && "Missing member specialization information?");
2512 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2513 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002514 DeclGroupRef DG(Var);
2515 Consumer.HandleTopLevelDecl(DG);
2516 }
Mike Stump1eb44332009-09-09 15:08:12 +00002517
Douglas Gregor7caa6822009-07-24 20:34:43 +00002518 if (Recursive) {
2519 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002520 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002521 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Douglas Gregor7caa6822009-07-24 20:34:43 +00002523 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002524 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002525 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002526}
Douglas Gregor815215d2009-05-27 05:35:12 +00002527
Anders Carlsson09025312009-08-29 05:16:22 +00002528void
2529Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2530 const CXXConstructorDecl *Tmpl,
2531 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Anders Carlsson09025312009-08-29 05:16:22 +00002533 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002534 bool AnyErrors = false;
2535
Anders Carlsson09025312009-08-29 05:16:22 +00002536 // Instantiate all the initializers.
2537 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002538 InitsEnd = Tmpl->init_end();
2539 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002540 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002541
Chandler Carruth030ef472010-09-03 21:54:20 +00002542 // Only instantiate written initializers, let Sema re-construct implicit
2543 // ones.
2544 if (!Init->isWritten())
2545 continue;
2546
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002547 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002548 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002549
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002550 SourceLocation EllipsisLoc;
2551
2552 if (Init->isPackExpansion()) {
2553 // This is a pack expansion. We should expand it now.
2554 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2555 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2556 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2557 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002558 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002559 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002560 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2561 BaseTL.getSourceRange(),
2562 Unexpanded.data(),
2563 Unexpanded.size(),
2564 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002565 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002566 NumExpansions)) {
2567 AnyErrors = true;
2568 New->setInvalidDecl();
2569 continue;
2570 }
2571 assert(ShouldExpand && "Partial instantiation of base initializer?");
2572
2573 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002574 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002575 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2576
2577 // Instantiate the initializer.
2578 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2579 LParenLoc, NewArgs, RParenLoc)) {
2580 AnyErrors = true;
2581 break;
2582 }
2583
2584 // Instantiate the base type.
2585 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2586 TemplateArgs,
2587 Init->getSourceLocation(),
2588 New->getDeclName());
2589 if (!BaseTInfo) {
2590 AnyErrors = true;
2591 break;
2592 }
2593
2594 // Build the initializer.
2595 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2596 BaseTInfo,
2597 (Expr **)NewArgs.data(),
2598 NewArgs.size(),
2599 Init->getLParenLoc(),
2600 Init->getRParenLoc(),
2601 New->getParent(),
2602 SourceLocation());
2603 if (NewInit.isInvalid()) {
2604 AnyErrors = true;
2605 break;
2606 }
2607
2608 NewInits.push_back(NewInit.get());
2609 NewArgs.clear();
2610 }
2611
2612 continue;
2613 }
2614
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002615 // Instantiate the initializer.
2616 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002617 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002618 AnyErrors = true;
2619 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002620 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002621
Anders Carlsson09025312009-08-29 05:16:22 +00002622 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002623 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002624 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002625 TemplateArgs,
2626 Init->getSourceLocation(),
2627 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002628 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002629 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002630 New->setInvalidDecl();
2631 continue;
2632 }
2633
John McCalla93c9342009-12-07 02:54:59 +00002634 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002635 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002636 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002637 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002638 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002639 New->getParent(),
2640 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002641 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002642 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002643 Init->getMemberLocation(),
2644 Init->getMember(),
2645 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002646 if (!Member) {
2647 AnyErrors = true;
2648 New->setInvalidDecl();
2649 continue;
2650 }
Mike Stump1eb44332009-09-09 15:08:12 +00002651
2652 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002653 NewArgs.size(),
2654 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002655 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002656 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002657 } else if (Init->isIndirectMemberInitializer()) {
2658 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002659 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002660 Init->getMemberLocation(),
2661 Init->getIndirectMember(), TemplateArgs));
2662
Douglas Gregorb7107222011-03-04 19:46:35 +00002663 if (!IndirectMember) {
2664 AnyErrors = true;
2665 New->setInvalidDecl();
2666 continue;
2667 }
2668
Francois Pichet00eb3f92010-12-04 09:14:42 +00002669 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2670 NewArgs.size(),
2671 Init->getSourceLocation(),
2672 Init->getLParenLoc(),
2673 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002674 }
2675
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002676 if (NewInit.isInvalid()) {
2677 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002678 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002679 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002680 // FIXME: It would be nice if ASTOwningVector had a release function.
2681 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Anders Carlsson09025312009-08-29 05:16:22 +00002683 NewInits.push_back((MemInitTy *)NewInit.get());
2684 }
2685 }
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Anders Carlsson09025312009-08-29 05:16:22 +00002687 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002688 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002689 /*FIXME: ColonLoc */
2690 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002691 NewInits.data(), NewInits.size(),
2692 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002693}
2694
John McCall52a575a2009-08-29 08:11:13 +00002695// TODO: this could be templated if the various decl types used the
2696// same method name.
2697static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2698 ClassTemplateDecl *Instance) {
2699 Pattern = Pattern->getCanonicalDecl();
2700
2701 do {
2702 Instance = Instance->getCanonicalDecl();
2703 if (Pattern == Instance) return true;
2704 Instance = Instance->getInstantiatedFromMemberTemplate();
2705 } while (Instance);
2706
2707 return false;
2708}
2709
Douglas Gregor0d696532009-09-28 06:34:35 +00002710static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2711 FunctionTemplateDecl *Instance) {
2712 Pattern = Pattern->getCanonicalDecl();
2713
2714 do {
2715 Instance = Instance->getCanonicalDecl();
2716 if (Pattern == Instance) return true;
2717 Instance = Instance->getInstantiatedFromMemberTemplate();
2718 } while (Instance);
2719
2720 return false;
2721}
2722
Douglas Gregored9c0f92009-10-29 00:04:11 +00002723static bool
2724isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2725 ClassTemplatePartialSpecializationDecl *Instance) {
2726 Pattern
2727 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2728 do {
2729 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2730 Instance->getCanonicalDecl());
2731 if (Pattern == Instance)
2732 return true;
2733 Instance = Instance->getInstantiatedFromMember();
2734 } while (Instance);
2735
2736 return false;
2737}
2738
John McCall52a575a2009-08-29 08:11:13 +00002739static bool isInstantiationOf(CXXRecordDecl *Pattern,
2740 CXXRecordDecl *Instance) {
2741 Pattern = Pattern->getCanonicalDecl();
2742
2743 do {
2744 Instance = Instance->getCanonicalDecl();
2745 if (Pattern == Instance) return true;
2746 Instance = Instance->getInstantiatedFromMemberClass();
2747 } while (Instance);
2748
2749 return false;
2750}
2751
2752static bool isInstantiationOf(FunctionDecl *Pattern,
2753 FunctionDecl *Instance) {
2754 Pattern = Pattern->getCanonicalDecl();
2755
2756 do {
2757 Instance = Instance->getCanonicalDecl();
2758 if (Pattern == Instance) return true;
2759 Instance = Instance->getInstantiatedFromMemberFunction();
2760 } while (Instance);
2761
2762 return false;
2763}
2764
2765static bool isInstantiationOf(EnumDecl *Pattern,
2766 EnumDecl *Instance) {
2767 Pattern = Pattern->getCanonicalDecl();
2768
2769 do {
2770 Instance = Instance->getCanonicalDecl();
2771 if (Pattern == Instance) return true;
2772 Instance = Instance->getInstantiatedFromMemberEnum();
2773 } while (Instance);
2774
2775 return false;
2776}
2777
John McCalled976492009-12-04 22:46:56 +00002778static bool isInstantiationOf(UsingShadowDecl *Pattern,
2779 UsingShadowDecl *Instance,
2780 ASTContext &C) {
2781 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2782}
2783
2784static bool isInstantiationOf(UsingDecl *Pattern,
2785 UsingDecl *Instance,
2786 ASTContext &C) {
2787 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2788}
2789
John McCall7ba107a2009-11-18 02:36:19 +00002790static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2791 UsingDecl *Instance,
2792 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002793 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002794}
2795
2796static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002797 UsingDecl *Instance,
2798 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002799 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002800}
2801
John McCall52a575a2009-08-29 08:11:13 +00002802static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2803 VarDecl *Instance) {
2804 assert(Instance->isStaticDataMember());
2805
2806 Pattern = Pattern->getCanonicalDecl();
2807
2808 do {
2809 Instance = Instance->getCanonicalDecl();
2810 if (Pattern == Instance) return true;
2811 Instance = Instance->getInstantiatedFromStaticDataMember();
2812 } while (Instance);
2813
2814 return false;
2815}
2816
John McCalled976492009-12-04 22:46:56 +00002817// Other is the prospective instantiation
2818// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002819static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002820 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002821 if (UnresolvedUsingTypenameDecl *UUD
2822 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2823 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2824 return isInstantiationOf(UUD, UD, Ctx);
2825 }
2826 }
2827
2828 if (UnresolvedUsingValueDecl *UUD
2829 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002830 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2831 return isInstantiationOf(UUD, UD, Ctx);
2832 }
2833 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002834
Anders Carlsson0d8df782009-08-29 19:37:28 +00002835 return false;
2836 }
Mike Stump1eb44332009-09-09 15:08:12 +00002837
John McCall52a575a2009-08-29 08:11:13 +00002838 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2839 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002840
John McCall52a575a2009-08-29 08:11:13 +00002841 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2842 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002843
John McCall52a575a2009-08-29 08:11:13 +00002844 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2845 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002846
Douglas Gregor7caa6822009-07-24 20:34:43 +00002847 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002848 if (Var->isStaticDataMember())
2849 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2850
2851 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2852 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002853
Douglas Gregor0d696532009-09-28 06:34:35 +00002854 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2855 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2856
Douglas Gregored9c0f92009-10-29 00:04:11 +00002857 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2858 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2859 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2860 PartialSpec);
2861
Anders Carlssond8b285f2009-09-01 04:26:58 +00002862 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2863 if (!Field->getDeclName()) {
2864 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002865 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002866 cast<FieldDecl>(D);
2867 }
2868 }
Mike Stump1eb44332009-09-09 15:08:12 +00002869
John McCalled976492009-12-04 22:46:56 +00002870 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2871 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2872
2873 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2874 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2875
Douglas Gregor815215d2009-05-27 05:35:12 +00002876 return D->getDeclName() && isa<NamedDecl>(Other) &&
2877 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2878}
2879
2880template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002881static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002882 NamedDecl *D,
2883 ForwardIterator first,
2884 ForwardIterator last) {
2885 for (; first != last; ++first)
2886 if (isInstantiationOf(Ctx, D, *first))
2887 return cast<NamedDecl>(*first);
2888
2889 return 0;
2890}
2891
John McCall02cace72009-08-28 07:59:38 +00002892/// \brief Finds the instantiation of the given declaration context
2893/// within the current instantiation.
2894///
2895/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002896DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002897 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002898 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002899 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002900 return cast_or_null<DeclContext>(ID);
2901 } else return DC;
2902}
2903
Douglas Gregored961e72009-05-27 17:54:46 +00002904/// \brief Find the instantiation of the given declaration within the
2905/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002906///
2907/// This routine is intended to be used when \p D is a declaration
2908/// referenced from within a template, that needs to mapped into the
2909/// corresponding declaration within an instantiation. For example,
2910/// given:
2911///
2912/// \code
2913/// template<typename T>
2914/// struct X {
2915/// enum Kind {
2916/// KnownValue = sizeof(T)
2917/// };
2918///
2919/// bool getKind() const { return KnownValue; }
2920/// };
2921///
2922/// template struct X<int>;
2923/// \endcode
2924///
2925/// In the instantiation of X<int>::getKind(), we need to map the
2926/// EnumConstantDecl for KnownValue (which refers to
2927/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002928/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2929/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002930NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002931 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002932 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002933 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002934 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002935 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002936 // D is a local of some kind. Look into the map of local
2937 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002938 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2939 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2940 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002941
Chris Lattner57ad3782011-02-17 20:34:02 +00002942 if (Found) {
2943 if (Decl *FD = Found->dyn_cast<Decl *>())
2944 return cast<NamedDecl>(FD);
2945
2946 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2947 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2948 }
2949
2950 // If we didn't find the decl, then we must have a label decl that hasn't
2951 // been found yet. Lazily instantiate it and return it now.
2952 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002953
Chris Lattner57ad3782011-02-17 20:34:02 +00002954 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2955 assert(Inst && "Failed to instantiate label??");
2956
2957 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2958 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002959 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002960
Douglas Gregore95b4092009-09-16 18:34:49 +00002961 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2962 if (!Record->isDependentContext())
2963 return D;
2964
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002965 // If the RecordDecl is actually the injected-class-name or a
2966 // "templated" declaration for a class template, class template
2967 // partial specialization, or a member class of a class template,
2968 // substitute into the injected-class-name of the class template
2969 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002970 QualType T;
2971 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2972
2973 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002974 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002975 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2976 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002977 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002978
2979 // If we call SubstType with an InjectedClassNameType here we
2980 // can end up in an infinite loop.
2981 T = Context.getTypeDeclType(Record);
2982 assert(isa<InjectedClassNameType>(T) &&
2983 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002984 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002985 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002986
2987 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002988 // Substitute into the injected-class-name to get the type
2989 // corresponding to the instantiation we want, which may also be
2990 // the current instantiation (if we're in a template
2991 // definition). This substitution should never fail, since we
2992 // know we can instantiate the injected-class-name or we
2993 // wouldn't have gotten to the injected-class-name!
2994
2995 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2996 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00002997 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00002998 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2999
3000 if (!T->isDependentType()) {
3001 assert(T->isRecordType() && "Instantiation must produce a record type");
3002 return T->getAs<RecordType>()->getDecl();
3003 }
3004
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003005 // We are performing "partial" template instantiation to create
3006 // the member declarations for the members of a class template
3007 // specialization. Therefore, D is actually referring to something
3008 // in the current instantiation. Look through the current
3009 // context, which contains actual instantiations, to find the
3010 // instantiation of the "current instantiation" that D refers
3011 // to.
3012 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003013 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00003014 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003015 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003016 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00003017 if (isInstantiationOf(ClassTemplate,
3018 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00003019 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003020
3021 if (!DC->isDependentContext())
3022 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00003023 }
3024
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003025 // We're performing "instantiation" of a member of the current
3026 // instantiation while we are type-checking the
3027 // definition. Compute the declaration context and return that.
3028 assert(!SawNonDependentContext &&
3029 "No dependent context while instantiating record");
3030 DeclContext *DC = computeDeclContext(T);
3031 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003032 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003033 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003034 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003035
Douglas Gregore95b4092009-09-16 18:34:49 +00003036 // Fall through to deal with other dependent record types (e.g.,
3037 // anonymous unions in class templates).
3038 }
John McCall52a575a2009-08-29 08:11:13 +00003039
Douglas Gregore95b4092009-09-16 18:34:49 +00003040 if (!ParentDC->isDependentContext())
3041 return D;
3042
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003043 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003044 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003045 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Douglas Gregor815215d2009-05-27 05:35:12 +00003047 if (ParentDC != D->getDeclContext()) {
3048 // We performed some kind of instantiation in the parent context,
3049 // so now we need to look into the instantiated parent context to
3050 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003051
John McCall3cb0ebd2010-03-10 03:28:59 +00003052 // If our context used to be dependent, we may need to instantiate
3053 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003054 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003055 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003056 if (!Spec->isDependentContext()) {
3057 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003058 const RecordType *Tag = T->getAs<RecordType>();
3059 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003060 if (Tag->isBeingDefined())
3061 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003062 if (!Tag->isBeingDefined() &&
3063 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3064 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003065
3066 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003067 }
3068 }
3069
Douglas Gregor815215d2009-05-27 05:35:12 +00003070 NamedDecl *Result = 0;
3071 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003072 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003073 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3074 } else {
3075 // Since we don't have a name for the entity we're looking for,
3076 // our only option is to walk through all of the declarations to
3077 // find that name. This will occur in a few cases:
3078 //
3079 // - anonymous struct/union within a template
3080 // - unnamed class/struct/union/enum within a template
3081 //
3082 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003083 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003084 ParentDC->decls_begin(),
3085 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003086 }
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003088 if (!Result) {
3089 if (isa<UsingShadowDecl>(D)) {
3090 // UsingShadowDecls can instantiate to nothing because of using hiding.
3091 } else if (Diags.hasErrorOccurred()) {
3092 // We've already complained about something, so most likely this
3093 // declaration failed to instantiate. There's no point in complaining
3094 // further, since this is normal in invalid code.
3095 } else if (IsBeingInstantiated) {
3096 // The class in which this member exists is currently being
3097 // instantiated, and we haven't gotten around to instantiating this
3098 // member yet. This can happen when the code uses forward declarations
3099 // of member classes, and introduces ordering dependencies via
3100 // template instantiation.
3101 Diag(Loc, diag::err_member_not_yet_instantiated)
3102 << D->getDeclName()
3103 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3104 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3105 } else {
3106 // We should have found something, but didn't.
3107 llvm_unreachable("Unable to find instantiation of declaration!");
3108 }
3109 }
3110
Douglas Gregor815215d2009-05-27 05:35:12 +00003111 D = Result;
3112 }
3113
Douglas Gregor815215d2009-05-27 05:35:12 +00003114 return D;
3115}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003116
Mike Stump1eb44332009-09-09 15:08:12 +00003117/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003118/// instantiations we have seen until this point.
Douglas Gregor78844032011-04-22 22:25:37 +00003119///
3120/// \returns true if anything was instantiated.
3121bool Sema::PerformPendingInstantiations(bool LocalOnly) {
3122 bool InstantiatedAnything = false;
Douglas Gregor60406be2010-01-16 22:29:39 +00003123 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003124 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003125 PendingImplicitInstantiation Inst;
3126
3127 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003128 Inst = PendingInstantiations.front();
3129 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003130 } else {
3131 Inst = PendingLocalImplicitInstantiations.front();
3132 PendingLocalImplicitInstantiations.pop_front();
3133 }
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Douglas Gregor7caa6822009-07-24 20:34:43 +00003135 // Instantiate function definitions
3136 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003137 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3138 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003139 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3140 TSK_ExplicitInstantiationDefinition;
3141 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3142 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003143 InstantiatedAnything = true;
Douglas Gregor7caa6822009-07-24 20:34:43 +00003144 continue;
3145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Douglas Gregor7caa6822009-07-24 20:34:43 +00003147 // Instantiate static data member definitions.
3148 VarDecl *Var = cast<VarDecl>(Inst.first);
3149 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003150
Chandler Carruth291b4412010-02-13 10:17:50 +00003151 // Don't try to instantiate declarations if the most recent redeclaration
3152 // is invalid.
3153 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3154 continue;
3155
3156 // Check if the most recent declaration has changed the specialization kind
3157 // and removed the need for implicit instantiation.
3158 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3159 case TSK_Undeclared:
3160 assert(false && "Cannot instantitiate an undeclared specialization.");
3161 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003162 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003163 continue; // No longer need to instantiate this type.
3164 case TSK_ExplicitInstantiationDefinition:
3165 // We only need an instantiation if the pending instantiation *is* the
3166 // explicit instantiation.
3167 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003168 case TSK_ImplicitInstantiation:
3169 break;
3170 }
3171
John McCallf312b1e2010-08-26 23:41:50 +00003172 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3173 "instantiating static data member "
3174 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Chandler Carruth58e390e2010-08-25 08:27:02 +00003176 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3177 TSK_ExplicitInstantiationDefinition;
3178 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3179 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003180 InstantiatedAnything = true;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003181 }
Douglas Gregor78844032011-04-22 22:25:37 +00003182
3183 return InstantiatedAnything;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003184}
John McCall0c01d182010-03-24 05:22:00 +00003185
3186void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3187 const MultiLevelTemplateArgumentList &TemplateArgs) {
3188 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3189 E = Pattern->ddiag_end(); I != E; ++I) {
3190 DependentDiagnostic *DD = *I;
3191
3192 switch (DD->getKind()) {
3193 case DependentDiagnostic::Access:
3194 HandleDependentAccessCheck(*DD, TemplateArgs);
3195 break;
3196 }
3197 }
3198}