blob: b6ef498874e4de3fc90432ec6017a425af396bbf [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) {
30 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
31 if (!OldQual) return false;
32
33 SourceRange QualRange = OldDecl->getQualifierRange();
34
35 NestedNameSpecifier *NewQual
36 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
37 if (!NewQual)
38 return true;
39
40 NewDecl->setQualifierInfo(NewQual, QualRange);
41 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
46 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
47 if (!OldQual) return false;
48
49 SourceRange QualRange = OldDecl->getQualifierRange();
50
51 NestedNameSpecifier *NewQual
52 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
53 if (!NewQual)
54 return true;
55
56 NewDecl->setQualifierInfo(NewQual, QualRange);
57 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 *
104TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
105 assert(false && "Namespaces cannot be instantiated");
106 return D;
107}
108
John McCall3dbd3d52010-02-16 06:53:13 +0000109Decl *
110TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
111 NamespaceAliasDecl *Inst
112 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
113 D->getNamespaceLoc(),
114 D->getAliasLoc(),
115 D->getNamespace()->getIdentifier(),
116 D->getQualifierRange(),
117 D->getQualifier(),
118 D->getTargetNameLoc(),
119 D->getNamespace());
120 Owner->addDecl(Inst);
121 return Inst;
122}
123
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000124Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
125 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000126 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000127 if (DI->getType()->isDependentType() ||
128 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000129 DI = SemaRef.SubstType(DI, TemplateArgs,
130 D->getLocation(), D->getDeclName());
131 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000132 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000133 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000134 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000135 } else {
136 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 // Create the new typedef
140 TypedefDecl *Typedef
141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000142 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 if (Invalid)
144 Typedef->setInvalidDecl();
145
Douglas Gregord57a38e2010-04-23 16:25:07 +0000146 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
147 TagDecl *TD = TT->getDecl();
148
149 // If the TagDecl that the TypedefDecl points to is an anonymous decl
150 // keep track of the TypedefDecl.
151 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
152 TD->setTypedefForAnonDecl(Typedef);
153 }
154
John McCall5126fd02009-12-30 00:31:22 +0000155 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000156 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
157 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000158 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
159 }
160
John McCall1d8d1cc2010-08-01 02:01:53 +0000161 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000162
John McCall46460a62010-01-20 21:53:11 +0000163 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000164 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000166 return Typedef;
167}
168
Douglas Gregor6eef5192009-12-14 19:27:10 +0000169/// \brief Instantiate the arguments provided as part of initialization.
170///
171/// \returns true if an error occurred, false otherwise.
172static bool InstantiateInitializationArguments(Sema &SemaRef,
173 Expr **Args, unsigned NumArgs,
174 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallca0408f2010-08-23 06:44:23 +0000175 ASTOwningVector<Expr*> &InitArgs) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176 for (unsigned I = 0; I != NumArgs; ++I) {
177 // When we hit the first defaulted argument, break out of the loop:
178 // we don't pass those default arguments on.
179 if (Args[I]->isDefaultArgument())
180 break;
181
John McCall60d7b3a2010-08-24 06:29:42 +0000182 ExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000183 if (Arg.isInvalid())
184 return true;
185
Douglas Gregor6eef5192009-12-14 19:27:10 +0000186 InitArgs.push_back(Arg.release());
Douglas Gregor6eef5192009-12-14 19:27:10 +0000187 }
188
189 return false;
190}
191
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000192/// \brief Instantiate an initializer, breaking it into separate
193/// initialization arguments.
194///
195/// \param S The semantic analysis object.
196///
197/// \param Init The initializer to instantiate.
198///
199/// \param TemplateArgs Template arguments to be substituted into the
200/// initializer.
201///
202/// \param NewArgs Will be filled in with the instantiation arguments.
203///
204/// \returns true if an error occurred, false otherwise
205static bool InstantiateInitializer(Sema &S, Expr *Init,
206 const MultiLevelTemplateArgumentList &TemplateArgs,
207 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000208 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000209 SourceLocation &RParenLoc) {
210 NewArgs.clear();
211 LParenLoc = SourceLocation();
212 RParenLoc = SourceLocation();
213
214 if (!Init)
215 return false;
216
John McCall4765fa02010-12-06 08:20:24 +0000217 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000218 Init = ExprTemp->getSubExpr();
219
220 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
221 Init = Binder->getSubExpr();
222
223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
224 Init = ICE->getSubExprAsWritten();
225
226 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
227 LParenLoc = ParenList->getLParenLoc();
228 RParenLoc = ParenList->getRParenLoc();
229 return InstantiateInitializationArguments(S, ParenList->getExprs(),
230 ParenList->getNumExprs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000231 TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000232 }
233
234 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000235 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
236 if (InstantiateInitializationArguments(S,
237 Construct->getArgs(),
238 Construct->getNumArgs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000239 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000240 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000241
Douglas Gregor28329e52010-03-24 21:22:47 +0000242 // FIXME: Fake locations!
243 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000244 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000245 return false;
246 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000247 }
248
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000250 if (Result.isInvalid())
251 return true;
252
253 NewArgs.push_back(Result.takeAs<Expr>());
254 return false;
255}
256
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000257Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000258 // If this is the variable for an anonymous struct or union,
259 // instantiate the anonymous struct/union type first.
260 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
261 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
262 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
263 return 0;
264
John McCallce3ff2b2009-08-25 22:02:44 +0000265 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000266 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000267 TemplateArgs,
268 D->getTypeSpecStartLoc(),
269 D->getDeclName());
270 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000271 return 0;
272
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000273 if (DI->getType()->isFunctionType()) {
274 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
275 << D->isStaticDataMember() << DI->getType();
276 return 0;
277 }
278
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000279 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000280 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
281 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());
Mike Stump1eb44332009-09-09 15:08:12 +0000287
John McCallb6217662010-03-15 10:12:16 +0000288 // Substitute the nested name specifier, if any.
289 if (SubstQualifier(D, Var))
290 return 0;
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000293 // out-of-line, the instantiation will have the same lexical
294 // context (which will be a namespace scope) as the template.
295 if (D->isOutOfLine())
296 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000297
John McCall46460a62010-01-20 21:53:11 +0000298 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000299
300 if (!D->isStaticDataMember())
301 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000302
Mike Stump390b4cc2009-05-16 07:39:55 +0000303 // FIXME: In theory, we could have a previous declaration for variables that
304 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000305 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000306 // FIXME: having to fake up a LookupResult is dumb.
307 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000308 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000309 if (D->isStaticDataMember())
310 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000311 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregor7caa6822009-07-24 20:34:43 +0000313 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000314 if (!D->isStaticDataMember())
315 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000316 Owner->makeDeclVisibleInContext(Var);
317 } else {
318 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000319 if (Owner->isFunctionOrMethod())
320 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000321 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000322 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000323
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000324 // Link instantiations of static data members back to the template from
325 // which they were instantiated.
326 if (Var->isStaticDataMember())
327 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000328 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000329
Douglas Gregor60c93c92010-02-09 07:26:29 +0000330 if (Var->getAnyInitializer()) {
331 // We already have an initializer in the class.
332 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000333 if (Var->isStaticDataMember() && !D->isOutOfLine())
334 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
335 else
336 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
337
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000338 // Instantiate the initializer.
339 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000340 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000342 InitArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000343 // Attach the initializer to the declaration.
344 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000345 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000346 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000347 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000348 move_arg(InitArgs),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000349 RParenLoc);
350 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000351 Expr *Init = InitArgs.take()[0];
352 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 } else {
354 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000355 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000356 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000357 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000358 // FIXME: Not too happy about invalidating the declaration
359 // because of a bogus initializer.
360 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000361 }
362
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000363 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000364 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000365 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000366
Douglas Gregor5764f612010-05-08 23:05:03 +0000367 // Diagnose unused local variables.
368 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
369 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000370
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000371 return Var;
372}
373
Abramo Bagnara6206d532010-06-05 05:09:32 +0000374Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
375 AccessSpecDecl* AD
376 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
377 D->getAccessSpecifierLoc(), D->getColonLoc());
378 Owner->addHiddenDecl(AD);
379 return AD;
380}
381
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
383 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000384 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000385 if (DI->getType()->isDependentType() ||
386 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000387 DI = SemaRef.SubstType(DI, TemplateArgs,
388 D->getLocation(), D->getDeclName());
389 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000390 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000391 Invalid = true;
392 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393 // C++ [temp.arg.type]p3:
394 // If a declaration acquires a function type through a type
395 // dependent on a template-parameter and this causes a
396 // declaration that does not use the syntactic form of a
397 // function declarator to have function type, the program is
398 // ill-formed.
399 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000400 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 Invalid = true;
402 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000403 } else {
404 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405 }
406
407 Expr *BitWidth = D->getBitWidth();
408 if (Invalid)
409 BitWidth = 0;
410 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000411 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000412 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
John McCall60d7b3a2010-08-24 06:29:42 +0000414 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000415 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 if (InstantiatedBitWidth.isInvalid()) {
417 Invalid = true;
418 BitWidth = 0;
419 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000420 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 }
422
John McCall07fb6be2009-10-22 23:33:21 +0000423 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
424 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000425 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000426 D->getLocation(),
427 D->isMutable(),
428 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000429 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 D->getAccess(),
431 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000432 if (!Field) {
433 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000434 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
John McCall1d8d1cc2010-08-01 02:01:53 +0000437 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000438
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000439 if (Invalid)
440 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 if (!Field->getDeclName()) {
443 // Keep track of where this decl came from.
444 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000445 }
446 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
447 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000448 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000452 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000453 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000454 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455
456 return Field;
457}
458
Francois Pichet87c2e122010-11-21 06:08:52 +0000459Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
460 NamedDecl **NamedChain =
461 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
462
463 int i = 0;
464 for (IndirectFieldDecl::chain_iterator PI =
465 D->chain_begin(), PE = D->chain_end();
466 PI != PE; ++PI)
467 NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
468 *PI, TemplateArgs));
469
Francois Pichet40e17752010-12-09 10:07:54 +0000470 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000471 IndirectFieldDecl* IndirectField
472 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000473 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000474 NamedChain, D->getChainingSize());
475
476
477 IndirectField->setImplicit(D->isImplicit());
478 IndirectField->setAccess(D->getAccess());
479 Owner->addDecl(IndirectField);
480 return IndirectField;
481}
482
John McCall02cace72009-08-28 07:59:38 +0000483Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000484 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000486 if (TypeSourceInfo *Ty = D->getFriendType()) {
487 TypeSourceInfo *InstTy =
488 SemaRef.SubstType(Ty, TemplateArgs,
489 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000490 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000491 return 0;
John McCall02cace72009-08-28 07:59:38 +0000492
Douglas Gregor06245bf2010-04-07 17:57:12 +0000493 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
494 if (!FD)
495 return 0;
496
497 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000498 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 Owner->addDecl(FD);
500 return FD;
501 }
502
503 NamedDecl *ND = D->getFriendDecl();
504 assert(ND && "friend decl must be a decl or a type!");
505
John McCallaf2094e2010-04-08 09:05:18 +0000506 // All of the Visit implementations for the various potential friend
507 // declarations have to be carefully written to work for friend
508 // objects, with the most important detail being that the target
509 // decl should almost certainly not be placed in Owner.
510 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000511 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
John McCall02cace72009-08-28 07:59:38 +0000513 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000514 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
515 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000516 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000517 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000518 Owner->addDecl(FD);
519 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000520}
521
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000522Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
523 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregorac7610d2009-06-22 20:57:11 +0000525 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000526 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000527
John McCall60d7b3a2010-08-24 06:29:42 +0000528 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000529 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000530 if (InstantiatedAssertExpr.isInvalid())
531 return 0;
532
John McCall60d7b3a2010-08-24 06:29:42 +0000533 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000534 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000535 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000536 InstantiatedAssertExpr.get(),
537 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000538}
539
540Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000541 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000543 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000544 /*PrevDecl=*/0, D->isScoped(),
545 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000546 if (D->isFixed()) {
547 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
548 // If we have type source information for the underlying type, it means it
549 // has been explicitly set by the user. Perform substitution on it before
550 // moving on.
551 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
552 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
553 TemplateArgs,
554 UnderlyingLoc,
555 DeclarationName()));
556
557 if (!Enum->getIntegerTypeSourceInfo())
558 Enum->setIntegerType(SemaRef.Context.IntTy);
559 }
560 else {
561 assert(!D->getIntegerType()->isDependentType()
562 && "Dependent type without type source info");
563 Enum->setIntegerType(D->getIntegerType());
564 }
565 }
566
John McCall5b629aa2010-10-22 23:36:17 +0000567 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
568
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000569 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000570 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000571 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000572 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573 Enum->startDefinition();
574
Douglas Gregor96084f12010-03-01 19:00:07 +0000575 if (D->getDeclContext()->isFunctionOrMethod())
576 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
577
John McCalld226f652010-08-21 09:40:31 +0000578 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579
580 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000581 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
582 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583 EC != ECEnd; ++EC) {
584 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000585 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000586 if (Expr *UninstValue = EC->getInitExpr()) {
587 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000588 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000589 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallce3ff2b2009-08-25 22:02:44 +0000591 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000592 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000593
594 // Drop the initial value and continue.
595 bool isInvalid = false;
596 if (Value.isInvalid()) {
597 Value = SemaRef.Owned((Expr *)0);
598 isInvalid = true;
599 }
600
Mike Stump1eb44332009-09-09 15:08:12 +0000601 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
603 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000604 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605
606 if (isInvalid) {
607 if (EnumConst)
608 EnumConst->setInvalidDecl();
609 Enum->setInvalidDecl();
610 }
611
612 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000613 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
614
John McCall3b85ecf2010-01-23 22:37:59 +0000615 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000616 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000617 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000618 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000619
620 if (D->getDeclContext()->isFunctionOrMethod()) {
621 // If the enumeration is within a function or method, record the enum
622 // constant as a local.
623 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
624 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000625 }
626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000628 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000629 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000630 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000631 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000632 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000633 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000634
635 return Enum;
636}
637
Douglas Gregor6477b692009-03-25 15:04:13 +0000638Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
639 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
640 return 0;
641}
642
John McCalle29ba202009-08-20 01:44:21 +0000643Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000644 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
645
Douglas Gregor550d9b22009-10-31 17:21:17 +0000646 // Create a local instantiation scope for this class template, which
647 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000648 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000649 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000650 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000651 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000652 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000653
654 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000655
656 // Instantiate the qualifier. We have to do this first in case
657 // we're a friend declaration, because if we are then we need to put
658 // the new declaration in the appropriate context.
659 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
660 if (Qualifier) {
661 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
662 Pattern->getQualifierRange(),
663 TemplateArgs);
664 if (!Qualifier) return 0;
665 }
666
667 CXXRecordDecl *PrevDecl = 0;
668 ClassTemplateDecl *PrevClassTemplate = 0;
669
Nick Lewycky37574f52010-11-08 23:29:42 +0000670 if (!isFriend && Pattern->getPreviousDeclaration()) {
671 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
672 if (Found.first != Found.second) {
673 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
674 if (PrevClassTemplate)
675 PrevDecl = PrevClassTemplate->getTemplatedDecl();
676 }
677 }
678
John McCall93ba8572010-03-25 06:39:04 +0000679 // If this isn't a friend, then it's a member template, in which
680 // case we just want to build the instantiation in the
681 // specialization. If it is a friend, we want to build it in
682 // the appropriate context.
683 DeclContext *DC = Owner;
684 if (isFriend) {
685 if (Qualifier) {
686 CXXScopeSpec SS;
687 SS.setScopeRep(Qualifier);
688 SS.setRange(Pattern->getQualifierRange());
689 DC = SemaRef.computeDeclContext(SS);
690 if (!DC) return 0;
691 } else {
692 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
693 Pattern->getDeclContext(),
694 TemplateArgs);
695 }
696
697 // Look for a previous declaration of the template in the owning
698 // context.
699 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
700 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
701 SemaRef.LookupQualifiedName(R, DC);
702
703 if (R.isSingleResult()) {
704 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
705 if (PrevClassTemplate)
706 PrevDecl = PrevClassTemplate->getTemplatedDecl();
707 }
708
709 if (!PrevClassTemplate && Qualifier) {
710 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000711 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
712 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000713 return 0;
714 }
715
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000716 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000717 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000718 bool Complain = true;
719
720 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
721 // template for struct std::tr1::__detail::_Map_base, where the
722 // template parameters of the friend declaration don't match the
723 // template parameters of the original declaration. In this one
724 // case, we don't complain about the ill-formed friend
725 // declaration.
726 if (isFriend && Pattern->getIdentifier() &&
727 Pattern->getIdentifier()->isStr("_Map_base") &&
728 DC->isNamespace() &&
729 cast<NamespaceDecl>(DC)->getIdentifier() &&
730 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
731 DeclContext *DCParent = DC->getParent();
732 if (DCParent->isNamespace() &&
733 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
734 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
735 DeclContext *DCParent2 = DCParent->getParent();
736 if (DCParent2->isNamespace() &&
737 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
738 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
739 DCParent2->getParent()->isTranslationUnit())
740 Complain = false;
741 }
742 }
743
John McCall93ba8572010-03-25 06:39:04 +0000744 TemplateParameterList *PrevParams
745 = PrevClassTemplate->getTemplateParameters();
746
747 // Make sure the parameter lists match.
748 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000749 Complain,
750 Sema::TPL_TemplateMatch)) {
751 if (Complain)
752 return 0;
753
754 AdoptedPreviousTemplateParams = true;
755 InstParams = PrevParams;
756 }
John McCall93ba8572010-03-25 06:39:04 +0000757
758 // Do some additional validation, then merge default arguments
759 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000760 if (!AdoptedPreviousTemplateParams &&
761 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000762 Sema::TPC_ClassTemplate))
763 return 0;
764 }
765 }
766
John McCalle29ba202009-08-20 01:44:21 +0000767 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000768 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000769 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000770 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000771 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000772
John McCall93ba8572010-03-25 06:39:04 +0000773 if (Qualifier)
774 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000775
John McCalle29ba202009-08-20 01:44:21 +0000776 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000777 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
778 D->getIdentifier(), InstParams, RecordInst,
779 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000780 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000781
John McCall93ba8572010-03-25 06:39:04 +0000782 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000783 if (PrevClassTemplate)
784 Inst->setAccess(PrevClassTemplate->getAccess());
785 else
786 Inst->setAccess(D->getAccess());
787
John McCall93ba8572010-03-25 06:39:04 +0000788 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
789 // TODO: do we want to track the instantiation progeny of this
790 // friend target decl?
791 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000792 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000793 if (!PrevClassTemplate)
794 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000795 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000796
797 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000798 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000799 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000800
Douglas Gregor259571e2009-10-30 22:42:42 +0000801 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000802 if (isFriend) {
803 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000804 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000805 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000806
John McCalle29ba202009-08-20 01:44:21 +0000807 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000808
809 if (!PrevClassTemplate) {
810 // Queue up any out-of-line partial specializations of this member
811 // class template; the client will force their instantiation once
812 // the enclosing class has been instantiated.
813 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
814 D->getPartialSpecializations(PartialSpecs);
815 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
816 if (PartialSpecs[I]->isOutOfLine())
817 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
818 }
819
John McCalle29ba202009-08-20 01:44:21 +0000820 return Inst;
821}
822
Douglas Gregord60e1052009-08-27 16:57:43 +0000823Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000824TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
825 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000826 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
827
828 // Lookup the already-instantiated declaration in the instantiation
829 // of the class template and return that.
830 DeclContext::lookup_result Found
831 = Owner->lookup(ClassTemplate->getDeclName());
832 if (Found.first == Found.second)
833 return 0;
834
835 ClassTemplateDecl *InstClassTemplate
836 = dyn_cast<ClassTemplateDecl>(*Found.first);
837 if (!InstClassTemplate)
838 return 0;
839
Douglas Gregord65587f2010-11-10 19:44:59 +0000840 if (ClassTemplatePartialSpecializationDecl *Result
841 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
842 return Result;
843
844 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000845}
846
847Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000848TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000849 // Create a local instantiation scope for this function template, which
850 // will contain the instantiations of the template parameters and then get
851 // merged with the local instantiation scope for the function template
852 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000853 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000854
Douglas Gregord60e1052009-08-27 16:57:43 +0000855 TemplateParameterList *TempParams = D->getTemplateParameters();
856 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000857 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000858 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000859
Douglas Gregora735b202009-10-13 14:39:41 +0000860 FunctionDecl *Instantiated = 0;
861 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
862 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
863 InstParams));
864 else
865 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
866 D->getTemplatedDecl(),
867 InstParams));
868
869 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 return 0;
871
John McCall46460a62010-01-20 21:53:11 +0000872 Instantiated->setAccess(D->getAccess());
873
Mike Stump1eb44332009-09-09 15:08:12 +0000874 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000875 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000876 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000877 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000878 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000879 assert(InstTemplate &&
880 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000881
John McCallb1a56e72010-03-26 23:10:15 +0000882 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
883
John McCalle976ffe2009-12-14 23:19:40 +0000884 // Link the instantiation back to the pattern *unless* this is a
885 // non-definition friend declaration.
886 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000887 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000888 InstTemplate->setInstantiatedFromMemberTemplate(D);
889
John McCallb1a56e72010-03-26 23:10:15 +0000890 // Make declarations visible in the appropriate context.
891 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000892 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000893
Douglas Gregord60e1052009-08-27 16:57:43 +0000894 return InstTemplate;
895}
896
Douglas Gregord475b8d2009-03-25 21:17:03 +0000897Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
898 CXXRecordDecl *PrevDecl = 0;
899 if (D->isInjectedClassName())
900 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000901 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000902 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
903 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000904 TemplateArgs);
905 if (!Prev) return 0;
906 PrevDecl = cast<CXXRecordDecl>(Prev);
907 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000908
909 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000910 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000911 D->getLocation(), D->getIdentifier(),
912 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000913
914 // Substitute the nested name specifier, if any.
915 if (SubstQualifier(D, Record))
916 return 0;
917
Douglas Gregord475b8d2009-03-25 21:17:03 +0000918 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000919 // FIXME: Check against AS_none is an ugly hack to work around the issue that
920 // the tag decls introduced by friend class declarations don't have an access
921 // specifier. Remove once this area of the code gets sorted out.
922 if (D->getAccess() != AS_none)
923 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000924 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000925 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926
John McCall02cace72009-08-28 07:59:38 +0000927 // If the original function was part of a friend declaration,
928 // inherit its namespace state.
929 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
930 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
931
Douglas Gregor9901c572010-05-21 00:31:19 +0000932 // Make sure that anonymous structs and unions are recorded.
933 if (D->isAnonymousStructOrUnion()) {
934 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000935 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000936 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
937 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000939 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000940 return Record;
941}
942
John McCall02cace72009-08-28 07:59:38 +0000943/// Normal class members are of more specific types and therefore
944/// don't make it here. This function serves two purposes:
945/// 1) instantiating function templates
946/// 2) substituting friend declarations
947/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000948Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000949 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000950 // Check whether there is already a function template specialization for
951 // this declaration.
952 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
953 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000954 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000955 std::pair<const TemplateArgument *, unsigned> Innermost
956 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000958 FunctionDecl *SpecFunc
959 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
960 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor127102b2009-06-29 20:59:39 +0000962 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000963 if (SpecFunc)
964 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCallb0cb0222010-03-27 05:57:59 +0000967 bool isFriend;
968 if (FunctionTemplate)
969 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
970 else
971 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
972
Douglas Gregor79c22782010-01-16 20:21:20 +0000973 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000974 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000975 !(isa<Decl>(Owner) &&
976 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000977 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregore53060f2009-06-25 22:08:12 +0000979 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000980 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
981 TInfo = SubstFunctionType(D, Params);
982 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000983 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000984 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000985
John McCalld325daa2010-03-26 04:53:08 +0000986 NestedNameSpecifier *Qualifier = D->getQualifier();
987 if (Qualifier) {
988 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
989 D->getQualifierRange(),
990 TemplateArgs);
991 if (!Qualifier) return 0;
992 }
993
John McCall68b6b872010-02-06 01:50:47 +0000994 // If we're instantiating a local function declaration, put the result
995 // in the owner; otherwise we need to find the instantiated context.
996 DeclContext *DC;
997 if (D->getDeclContext()->isFunctionOrMethod())
998 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000999 else if (isFriend && Qualifier) {
1000 CXXScopeSpec SS;
1001 SS.setScopeRep(Qualifier);
1002 SS.setRange(D->getQualifierRange());
1003 DC = SemaRef.computeDeclContext(SS);
1004 if (!DC) return 0;
1005 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001006 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1007 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001008 }
John McCall68b6b872010-02-06 01:50:47 +00001009
John McCall02cace72009-08-28 07:59:38 +00001010 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001011 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001012 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001013 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001014 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001015
John McCalld325daa2010-03-26 04:53:08 +00001016 if (Qualifier)
1017 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001018
John McCallb1a56e72010-03-26 23:10:15 +00001019 DeclContext *LexicalDC = Owner;
1020 if (!isFriend && D->isOutOfLine()) {
1021 assert(D->getDeclContext()->isFileContext());
1022 LexicalDC = D->getDeclContext();
1023 }
1024
1025 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregore53060f2009-06-25 22:08:12 +00001027 // Attach the parameters
1028 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001029 if (Params[P])
1030 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001031 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001032
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001033 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001034 if (TemplateParams) {
1035 // Our resulting instantiation is actually a function template, since we
1036 // are substituting only the outer template parameters. For example, given
1037 //
1038 // template<typename T>
1039 // struct X {
1040 // template<typename U> friend void f(T, U);
1041 // };
1042 //
1043 // X<int> x;
1044 //
1045 // We are instantiating the friend function template "f" within X<int>,
1046 // which means substituting int for T, but leaving "f" as a friend function
1047 // template.
1048 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001049 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001050 Function->getLocation(),
1051 Function->getDeclName(),
1052 TemplateParams, Function);
1053 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001054
1055 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001056
1057 if (isFriend && D->isThisDeclarationADefinition()) {
1058 // TODO: should we remember this connection regardless of whether
1059 // the friend declaration provided a body?
1060 FunctionTemplate->setInstantiatedFromMemberTemplate(
1061 D->getDescribedFunctionTemplate());
1062 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001063 } else if (FunctionTemplate) {
1064 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001065 std::pair<const TemplateArgument *, unsigned> Innermost
1066 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001067 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001068 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001069 Innermost.first,
1070 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001071 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001072 } else if (isFriend && D->isThisDeclarationADefinition()) {
1073 // TODO: should we remember this connection regardless of whether
1074 // the friend declaration provided a body?
1075 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001076 }
Douglas Gregora735b202009-10-13 14:39:41 +00001077
Douglas Gregore53060f2009-06-25 22:08:12 +00001078 if (InitFunctionInstantiation(Function, D))
1079 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregore53060f2009-06-25 22:08:12 +00001081 bool Redeclaration = false;
1082 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001083 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001084
John McCall68263142009-11-18 22:49:29 +00001085 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1086 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1087
John McCallaf2094e2010-04-08 09:05:18 +00001088 if (DependentFunctionTemplateSpecializationInfo *Info
1089 = D->getDependentSpecializationInfo()) {
1090 assert(isFriend && "non-friend has dependent specialization info?");
1091
1092 // This needs to be set now for future sanity.
1093 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1094
1095 // Instantiate the explicit template arguments.
1096 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1097 Info->getRAngleLoc());
1098 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1099 TemplateArgumentLoc Loc;
1100 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1101 return 0;
1102
1103 ExplicitArgs.addArgument(Loc);
1104 }
1105
1106 // Map the candidate templates to their instantiations.
1107 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1108 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1109 Info->getTemplate(I),
1110 TemplateArgs);
1111 if (!Temp) return 0;
1112
1113 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1114 }
1115
1116 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1117 &ExplicitArgs,
1118 Previous))
1119 Function->setInvalidDecl();
1120
1121 isExplicitSpecialization = true;
1122
1123 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001124 // Look only into the namespace where the friend would be declared to
1125 // find a previous declaration. This is the innermost enclosing namespace,
1126 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001127 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001128
Douglas Gregora735b202009-10-13 14:39:41 +00001129 // In C++, the previous declaration we find might be a tag type
1130 // (class or enum). In this case, the new declaration will hide the
1131 // tag type. Note that this does does not apply if we're declaring a
1132 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001133 if (Previous.isSingleTagDecl())
1134 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001135 }
1136
John McCall9f54ad42009-12-10 09:41:52 +00001137 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001138 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001139 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001140
John McCall76d32642010-04-24 01:30:58 +00001141 NamedDecl *PrincipalDecl = (TemplateParams
1142 ? cast<NamedDecl>(FunctionTemplate)
1143 : Function);
1144
Douglas Gregora735b202009-10-13 14:39:41 +00001145 // If the original function was part of a friend declaration,
1146 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001147 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001148 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001149 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001150 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001151 else
Douglas Gregora735b202009-10-13 14:39:41 +00001152 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001153
1154 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1155 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001156
Gabor Greif77535df2010-08-30 22:25:56 +00001157 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001158
Douglas Gregor238058c2010-05-18 05:45:02 +00001159 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1160 D->isThisDeclarationADefinition()) {
1161 // Check for a function body.
1162 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001163 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001164 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1165 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1166 << Function->getDeclName();
1167 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1168 Function->setInvalidDecl();
1169 }
1170 // Check for redefinitions due to other instantiations of this or
1171 // a similar friend function.
1172 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1173 REnd = Function->redecls_end();
1174 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001175 if (*R == Function)
1176 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001177 switch (R->getFriendObjectKind()) {
1178 case Decl::FOK_None:
1179 if (!queuedInstantiation && R->isUsed(false)) {
1180 if (MemberSpecializationInfo *MSInfo
1181 = Function->getMemberSpecializationInfo()) {
1182 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1183 SourceLocation Loc = R->getLocation(); // FIXME
1184 MSInfo->setPointOfInstantiation(Loc);
1185 SemaRef.PendingLocalImplicitInstantiations.push_back(
1186 std::make_pair(Function, Loc));
1187 queuedInstantiation = true;
1188 }
1189 }
1190 }
1191 break;
1192 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001193 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001194 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001195 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001196 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1197 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001198 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001199 Function->setInvalidDecl();
1200 break;
1201 }
1202 }
1203 }
1204 }
Douglas Gregora735b202009-10-13 14:39:41 +00001205 }
1206
John McCall76d32642010-04-24 01:30:58 +00001207 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1208 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1209 PrincipalDecl->setNonMemberOperator();
1210
Douglas Gregore53060f2009-06-25 22:08:12 +00001211 return Function;
1212}
1213
Douglas Gregord60e1052009-08-27 16:57:43 +00001214Decl *
1215TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1216 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001217 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1218 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001219 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001220 // We are creating a function template specialization from a function
1221 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001222 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001223 std::pair<const TemplateArgument *, unsigned> Innermost
1224 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001226 FunctionDecl *SpecFunc
1227 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1228 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregor6b906862009-08-21 00:16:32 +00001230 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001231 if (SpecFunc)
1232 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001233 }
1234
John McCallb0cb0222010-03-27 05:57:59 +00001235 bool isFriend;
1236 if (FunctionTemplate)
1237 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1238 else
1239 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1240
Douglas Gregor79c22782010-01-16 20:21:20 +00001241 bool MergeWithParentScope = (TemplateParams != 0) ||
1242 !(isa<Decl>(Owner) &&
1243 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001244 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001245
John McCall4eab39f2010-10-19 02:26:41 +00001246 // Instantiate enclosing template arguments for friends.
1247 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1248 unsigned NumTempParamLists = 0;
1249 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1250 TempParamLists.set_size(NumTempParamLists);
1251 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1252 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1253 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1254 if (!InstParams)
1255 return NULL;
1256 TempParamLists[I] = InstParams;
1257 }
1258 }
1259
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001260 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001261 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1262 TInfo = SubstFunctionType(D, Params);
1263 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001264 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001265 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001266
Abramo Bagnara723df242010-12-14 22:11:44 +00001267 // \brief If the type of this function, after ignoring parentheses,
1268 // is not *directly* a function type, then we're instantiating a function
1269 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001270 //
1271 // typedef int functype(int, int);
1272 // functype func;
1273 //
1274 // In this case, we'll just go instantiate the ParmVarDecls that we
1275 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001276 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001277 assert(!Params.size() && "Instantiating type could not yield parameters");
1278 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1279 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1280 TemplateArgs);
1281 if (!P)
1282 return 0;
1283
1284 Params.push_back(P);
1285 }
1286 }
1287
John McCallb0cb0222010-03-27 05:57:59 +00001288 NestedNameSpecifier *Qualifier = D->getQualifier();
1289 if (Qualifier) {
1290 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1291 D->getQualifierRange(),
1292 TemplateArgs);
1293 if (!Qualifier) return 0;
1294 }
1295
1296 DeclContext *DC = Owner;
1297 if (isFriend) {
1298 if (Qualifier) {
1299 CXXScopeSpec SS;
1300 SS.setScopeRep(Qualifier);
1301 SS.setRange(D->getQualifierRange());
1302 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001303
1304 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1305 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001306 } else {
1307 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1308 D->getDeclContext(),
1309 TemplateArgs);
1310 }
1311 if (!DC) return 0;
1312 }
1313
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001314 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001315 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001316 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Abramo Bagnara25777432010-08-11 22:01:17 +00001318 DeclarationNameInfo NameInfo
1319 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001320 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001321 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001322 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001323 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001324 Constructor->isInlineSpecified(),
1325 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001326 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001327 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001328 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001329 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001330 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001331 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001332 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001333 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001334 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001335 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001336 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001337 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1338 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001339 D->isStatic(),
1340 D->getStorageClassAsWritten(),
1341 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001342 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001343
John McCallb0cb0222010-03-27 05:57:59 +00001344 if (Qualifier)
1345 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001346
Douglas Gregord60e1052009-08-27 16:57:43 +00001347 if (TemplateParams) {
1348 // Our resulting instantiation is actually a function template, since we
1349 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001350 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001351 // template<typename T>
1352 // struct X {
1353 // template<typename U> void f(T, U);
1354 // };
1355 //
1356 // X<int> x;
1357 //
1358 // We are instantiating the member template "f" within X<int>, which means
1359 // substituting int for T, but leaving "f" as a member function template.
1360 // Build the function template itself.
1361 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1362 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001363 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001364 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001365 if (isFriend) {
1366 FunctionTemplate->setLexicalDeclContext(Owner);
1367 FunctionTemplate->setObjectOfFriendDecl(true);
1368 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001369 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001370 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001371 } else if (FunctionTemplate) {
1372 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001373 std::pair<const TemplateArgument *, unsigned> Innermost
1374 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001375 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001376 TemplateArgumentList::CreateCopy(SemaRef.Context,
1377 Innermost.first,
1378 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001379 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001380 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001381 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001382 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001383 }
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001386 // out-of-line, the instantiation will have the same lexical
1387 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001388 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001389 if (NumTempParamLists)
1390 Method->setTemplateParameterListsInfo(SemaRef.Context,
1391 NumTempParamLists,
1392 TempParamLists.data());
1393
John McCallb0cb0222010-03-27 05:57:59 +00001394 Method->setLexicalDeclContext(Owner);
1395 Method->setObjectOfFriendDecl(true);
1396 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001397 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregor5545e162009-03-24 00:38:23 +00001399 // Attach the parameters
1400 for (unsigned P = 0; P < Params.size(); ++P)
1401 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001402 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001403
1404 if (InitMethodInstantiation(Method, D))
1405 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001406
Abramo Bagnara25777432010-08-11 22:01:17 +00001407 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1408 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCallb0cb0222010-03-27 05:57:59 +00001410 if (!FunctionTemplate || TemplateParams || isFriend) {
1411 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregordec06662009-08-21 18:42:58 +00001413 // In C++, the previous declaration we find might be a tag type
1414 // (class or enum). In this case, the new declaration will hide the
1415 // tag type. Note that this does does not apply if we're declaring a
1416 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001417 if (Previous.isSingleTagDecl())
1418 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001419 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001420
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001421 bool Redeclaration = false;
1422 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001423 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001424 /*FIXME:*/OverloadableAttrRequired);
1425
Douglas Gregor4ba31362009-12-01 17:24:26 +00001426 if (D->isPure())
1427 SemaRef.CheckPureMethod(Method, SourceRange());
1428
John McCall46460a62010-01-20 21:53:11 +00001429 Method->setAccess(D->getAccess());
1430
John McCallb0cb0222010-03-27 05:57:59 +00001431 if (FunctionTemplate) {
1432 // If there's a function template, let our caller handle it.
1433 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1434 // Don't hide a (potentially) valid declaration with an invalid one.
1435 } else {
1436 NamedDecl *DeclToAdd = (TemplateParams
1437 ? cast<NamedDecl>(FunctionTemplate)
1438 : Method);
1439 if (isFriend)
1440 Record->makeDeclVisibleInContext(DeclToAdd);
1441 else
1442 Owner->addDecl(DeclToAdd);
1443 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001444
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001445 return Method;
1446}
1447
Douglas Gregor615c5d42009-03-24 16:43:20 +00001448Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001449 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001450}
1451
Douglas Gregor03b2b072009-03-24 00:15:49 +00001452Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001453 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001454}
1455
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001456Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001457 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001458}
1459
Douglas Gregor6477b692009-03-25 15:04:13 +00001460ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001461 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001462}
1463
John McCalle29ba202009-08-20 01:44:21 +00001464Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1465 TemplateTypeParmDecl *D) {
1466 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001467 const Type* T = D->getTypeForDecl();
1468 assert(T->isTemplateTypeParmType());
1469 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
John McCalle29ba202009-08-20 01:44:21 +00001471 TemplateTypeParmDecl *Inst =
1472 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001473 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001474 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001475 D->wasDeclaredWithTypename(),
1476 D->isParameterPack());
1477
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001478 if (D->hasDefaultArgument())
1479 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001480
Douglas Gregor550d9b22009-10-31 17:21:17 +00001481 // Introduce this template parameter's instantiation into the instantiation
1482 // scope.
1483 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1484
John McCalle29ba202009-08-20 01:44:21 +00001485 return Inst;
1486}
1487
Douglas Gregor33642df2009-10-23 23:25:44 +00001488Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1489 NonTypeTemplateParmDecl *D) {
1490 // Substitute into the type of the non-type template parameter.
1491 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001492 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001493 if (DI) {
1494 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1495 D->getDeclName());
1496 if (DI) T = DI->getType();
1497 } else {
1498 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1499 D->getDeclName());
1500 DI = 0;
1501 }
1502 if (T.isNull())
1503 return 0;
1504
1505 // Check that this type is acceptable for a non-type template parameter.
1506 bool Invalid = false;
1507 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1508 if (T.isNull()) {
1509 T = SemaRef.Context.IntTy;
1510 Invalid = true;
1511 }
1512
1513 NonTypeTemplateParmDecl *Param
1514 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001515 D->getDepth() - TemplateArgs.getNumLevels(),
1516 D->getPosition(), D->getIdentifier(), T,
1517 DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001518 if (Invalid)
1519 Param->setInvalidDecl();
1520
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001521 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001522
1523 // Introduce this template parameter's instantiation into the instantiation
1524 // scope.
1525 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001526 return Param;
1527}
1528
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001529Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001530TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1531 TemplateTemplateParmDecl *D) {
1532 // Instantiate the template parameter list of the template template parameter.
1533 TemplateParameterList *TempParams = D->getTemplateParameters();
1534 TemplateParameterList *InstParams;
1535 {
1536 // Perform the actual substitution of template parameters within a new,
1537 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001538 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001539 InstParams = SubstTemplateParams(TempParams);
1540 if (!InstParams)
1541 return NULL;
1542 }
1543
1544 // Build the template template parameter.
1545 TemplateTemplateParmDecl *Param
1546 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001547 D->getDepth() - TemplateArgs.getNumLevels(),
1548 D->getPosition(), D->getIdentifier(),
1549 InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001550 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001551
Douglas Gregor9106ef72009-11-11 16:58:32 +00001552 // Introduce this template parameter's instantiation into the instantiation
1553 // scope.
1554 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1555
1556 return Param;
1557}
1558
Douglas Gregor48c32a72009-11-17 06:07:40 +00001559Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1560 // Using directives are never dependent, so they require no explicit
1561
1562 UsingDirectiveDecl *Inst
1563 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1564 D->getNamespaceKeyLocation(),
1565 D->getQualifierRange(), D->getQualifier(),
1566 D->getIdentLocation(),
1567 D->getNominatedNamespace(),
1568 D->getCommonAncestor());
1569 Owner->addDecl(Inst);
1570 return Inst;
1571}
1572
John McCalled976492009-12-04 22:46:56 +00001573Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001574
1575 // The nested name specifier may be dependent, for example
1576 // template <typename T> struct t {
1577 // struct s1 { T f1(); };
1578 // struct s2 : s1 { using s1::f1; };
1579 // };
1580 // template struct t<int>;
1581 // Here, in using s1::f1, s1 refers to t<T>::s1;
1582 // we need to substitute for t<int>::s1.
1583 NestedNameSpecifier *NNS =
1584 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1585 D->getNestedNameRange(),
1586 TemplateArgs);
1587 if (!NNS)
1588 return 0;
1589
1590 // The name info is non-dependent, so no transformation
1591 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001592 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001593
John McCall9f54ad42009-12-10 09:41:52 +00001594 // We only need to do redeclaration lookups if we're in a class
1595 // scope (in fact, it's not really even possible in non-class
1596 // scopes).
1597 bool CheckRedeclaration = Owner->isRecord();
1598
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001599 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1600 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001601
John McCalled976492009-12-04 22:46:56 +00001602 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001603 D->getNestedNameRange(),
1604 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001605 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001606 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001607 D->isTypeName());
1608
1609 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001610 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001611 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001612
1613 if (CheckRedeclaration) {
1614 Prev.setHideTags(false);
1615 SemaRef.LookupQualifiedName(Prev, Owner);
1616
1617 // Check for invalid redeclarations.
1618 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1619 D->isTypeName(), SS,
1620 D->getLocation(), Prev))
1621 NewUD->setInvalidDecl();
1622
1623 }
1624
1625 if (!NewUD->isInvalidDecl() &&
1626 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001627 D->getLocation()))
1628 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001629
John McCalled976492009-12-04 22:46:56 +00001630 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1631 NewUD->setAccess(D->getAccess());
1632 Owner->addDecl(NewUD);
1633
John McCall9f54ad42009-12-10 09:41:52 +00001634 // Don't process the shadow decls for an invalid decl.
1635 if (NewUD->isInvalidDecl())
1636 return NewUD;
1637
John McCall323c3102009-12-22 22:26:37 +00001638 bool isFunctionScope = Owner->isFunctionOrMethod();
1639
John McCall9f54ad42009-12-10 09:41:52 +00001640 // Process the shadow decls.
1641 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1642 I != E; ++I) {
1643 UsingShadowDecl *Shadow = *I;
1644 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001645 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1646 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001647 TemplateArgs));
1648
1649 if (CheckRedeclaration &&
1650 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1651 continue;
1652
1653 UsingShadowDecl *InstShadow
1654 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1655 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001656
1657 if (isFunctionScope)
1658 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001659 }
John McCalled976492009-12-04 22:46:56 +00001660
1661 return NewUD;
1662}
1663
1664Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001665 // Ignore these; we handle them in bulk when processing the UsingDecl.
1666 return 0;
John McCalled976492009-12-04 22:46:56 +00001667}
1668
John McCall7ba107a2009-11-18 02:36:19 +00001669Decl * TemplateDeclInstantiator
1670 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001671 NestedNameSpecifier *NNS =
1672 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1673 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001674 TemplateArgs);
1675 if (!NNS)
1676 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001678 CXXScopeSpec SS;
1679 SS.setRange(D->getTargetNestedNameRange());
1680 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001682 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1683 // Hence, no tranformation is required for it.
1684 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001685 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001686 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001687 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001688 /*instantiation*/ true,
1689 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001690 if (UD)
John McCalled976492009-12-04 22:46:56 +00001691 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1692
John McCall7ba107a2009-11-18 02:36:19 +00001693 return UD;
1694}
1695
1696Decl * TemplateDeclInstantiator
1697 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1698 NestedNameSpecifier *NNS =
1699 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1700 D->getTargetNestedNameRange(),
1701 TemplateArgs);
1702 if (!NNS)
1703 return 0;
1704
1705 CXXScopeSpec SS;
1706 SS.setRange(D->getTargetNestedNameRange());
1707 SS.setScopeRep(NNS);
1708
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001709 DeclarationNameInfo NameInfo
1710 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1711
John McCall7ba107a2009-11-18 02:36:19 +00001712 NamedDecl *UD =
1713 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001714 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001715 /*instantiation*/ true,
1716 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001717 if (UD)
John McCalled976492009-12-04 22:46:56 +00001718 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1719
Anders Carlsson0d8df782009-08-29 19:37:28 +00001720 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001721}
1722
John McCallce3ff2b2009-08-25 22:02:44 +00001723Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001724 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001725 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001726 if (D->isInvalidDecl())
1727 return 0;
1728
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001729 return Instantiator.Visit(D);
1730}
1731
John McCalle29ba202009-08-20 01:44:21 +00001732/// \brief Instantiates a nested template parameter list in the current
1733/// instantiation context.
1734///
1735/// \param L The parameter list to instantiate
1736///
1737/// \returns NULL if there was an error
1738TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001739TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001740 // Get errors for all the parameters before bailing out.
1741 bool Invalid = false;
1742
1743 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001744 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001745 ParamVector Params;
1746 Params.reserve(N);
1747 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1748 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001749 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001750 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001751 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001752 }
1753
1754 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001755 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001756 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001757
1758 TemplateParameterList *InstL
1759 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1760 L->getLAngleLoc(), &Params.front(), N,
1761 L->getRAngleLoc());
1762 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001763}
John McCalle29ba202009-08-20 01:44:21 +00001764
Douglas Gregored9c0f92009-10-29 00:04:11 +00001765/// \brief Instantiate the declaration of a class template partial
1766/// specialization.
1767///
1768/// \param ClassTemplate the (instantiated) class template that is partially
1769// specialized by the instantiation of \p PartialSpec.
1770///
1771/// \param PartialSpec the (uninstantiated) class template partial
1772/// specialization that we are instantiating.
1773///
Douglas Gregord65587f2010-11-10 19:44:59 +00001774/// \returns The instantiated partial specialization, if successful; otherwise,
1775/// NULL to indicate an error.
1776ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001777TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1778 ClassTemplateDecl *ClassTemplate,
1779 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001780 // Create a local instantiation scope for this class template partial
1781 // specialization, which will contain the instantiations of the template
1782 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001783 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001784
Douglas Gregored9c0f92009-10-29 00:04:11 +00001785 // Substitute into the template parameters of the class template partial
1786 // specialization.
1787 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1788 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1789 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001790 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001791
1792 // Substitute into the template arguments of the class template partial
1793 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001794 const TemplateArgumentLoc *PartialSpecTemplateArgs
1795 = PartialSpec->getTemplateArgsAsWritten();
1796 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1797
John McCalld5532b62009-11-23 01:53:49 +00001798 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001799 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001800 TemplateArgumentLoc Loc;
1801 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregord65587f2010-11-10 19:44:59 +00001802 return 0;
John McCalld5532b62009-11-23 01:53:49 +00001803 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001804 }
1805
1806
1807 // Check that the template argument list is well-formed for this
1808 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001809 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001810 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1811 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001812 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001813 false,
1814 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001815 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001816
1817 // Figure out where to insert this class template partial specialization
1818 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001819 void *InsertPos = 0;
1820 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001821 = ClassTemplate->findPartialSpecialization(Converted.data(),
1822 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001823
1824 // Build the canonical type that describes the converted template
1825 // arguments of the class template partial specialization.
1826 QualType CanonType
1827 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001828 Converted.data(),
1829 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001830
1831 // Build the fully-sugared type for this class template
1832 // specialization as the user wrote in the specialization
1833 // itself. This means that we'll pretty-print the type retrieved
1834 // from the specialization's declaration the way that the user
1835 // actually wrote the specialization, rather than formatting the
1836 // name based on the "canonical" representation used to store the
1837 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001838 TypeSourceInfo *WrittenTy
1839 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1840 TemplateName(ClassTemplate),
1841 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001842 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001843 CanonType);
1844
1845 if (PrevDecl) {
1846 // We've already seen a partial specialization with the same template
1847 // parameters and template arguments. This can happen, for example, when
1848 // substituting the outer template arguments ends up causing two
1849 // class template partial specializations of a member class template
1850 // to have identical forms, e.g.,
1851 //
1852 // template<typename T, typename U>
1853 // struct Outer {
1854 // template<typename X, typename Y> struct Inner;
1855 // template<typename Y> struct Inner<T, Y>;
1856 // template<typename Y> struct Inner<U, Y>;
1857 // };
1858 //
1859 // Outer<int, int> outer; // error: the partial specializations of Inner
1860 // // have the same signature.
1861 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001862 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001863 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1864 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001865 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001866 }
1867
1868
1869 // Create the class template partial specialization declaration.
1870 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001871 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1872 PartialSpec->getTagKind(),
1873 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001874 PartialSpec->getLocation(),
1875 InstParams,
1876 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001877 Converted.data(),
1878 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001879 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001880 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001881 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001882 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001883 // Substitute the nested name specifier, if any.
1884 if (SubstQualifier(PartialSpec, InstPartialSpec))
1885 return 0;
1886
Douglas Gregored9c0f92009-10-29 00:04:11 +00001887 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001888 InstPartialSpec->setTypeAsWritten(WrittenTy);
1889
Douglas Gregored9c0f92009-10-29 00:04:11 +00001890 // Add this partial specialization to the set of class template partial
1891 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001892 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001893 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001894}
1895
John McCall21ef0fa2010-03-11 09:03:00 +00001896TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001897TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001898 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001899 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1900 assert(OldTInfo && "substituting function without type source info");
1901 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001902 TypeSourceInfo *NewTInfo
1903 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1904 D->getTypeSpecStartLoc(),
1905 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001906 if (!NewTInfo)
1907 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001908
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001909 if (NewTInfo != OldTInfo) {
1910 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001911 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001912 if (FunctionProtoTypeLoc *OldProtoLoc
1913 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001914 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001915 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1916 assert(NewProtoLoc && "Missing prototype?");
1917 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1918 // FIXME: Variadic templates will break this.
1919 Params.push_back(NewProtoLoc->getArg(i));
1920 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001921 OldProtoLoc->getArg(i),
1922 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001923 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001924 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001925 } else {
1926 // The function type itself was not dependent and therefore no
1927 // substitution occurred. However, we still need to instantiate
1928 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001929 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001930 if (FunctionProtoTypeLoc *OldProtoLoc
1931 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1932 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1933 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1934 if (!Parm)
1935 return 0;
1936 Params.push_back(Parm);
1937 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001938 }
1939 }
John McCall21ef0fa2010-03-11 09:03:00 +00001940 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001941}
1942
Mike Stump1eb44332009-09-09 15:08:12 +00001943/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001944/// declaration (New) from the corresponding fields of its template (Tmpl).
1945///
1946/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001947bool
1948TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001949 FunctionDecl *Tmpl) {
1950 if (Tmpl->isDeleted())
1951 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Douglas Gregorcca9e962009-07-01 22:01:06 +00001953 // If we are performing substituting explicitly-specified template arguments
1954 // or deduced template arguments into a function template and we reach this
1955 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001956 // to keeping the new function template specialization. We therefore
1957 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001958 // into a template instantiation for this specific function template
1959 // specialization, which is not a SFINAE context, so that we diagnose any
1960 // further errors in the declaration itself.
1961 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1962 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1963 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1964 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001965 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001966 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001967 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001968 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001969 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001970 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1971 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001972 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001973 }
1974 }
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001976 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1977 assert(Proto && "Function template without prototype?");
1978
1979 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1980 Proto->getNoReturnAttr()) {
1981 // The function has an exception specification or a "noreturn"
1982 // attribute. Substitute into each of the exception types.
1983 llvm::SmallVector<QualType, 4> Exceptions;
1984 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1985 // FIXME: Poor location information!
1986 QualType T
1987 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1988 New->getLocation(), New->getDeclName());
1989 if (T.isNull() ||
1990 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1991 continue;
1992
1993 Exceptions.push_back(T);
1994 }
1995
1996 // Rebuild the function type
1997
John McCalle23cf432010-12-14 08:05:40 +00001998 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
1999 EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2000 EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2001 EPI.NumExceptions = Exceptions.size();
2002 EPI.Exceptions = Exceptions.data();
2003 EPI.ExtInfo = Proto->getExtInfo();
2004
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002005 const FunctionProtoType *NewProto
2006 = New->getType()->getAs<FunctionProtoType>();
2007 assert(NewProto && "Template instantiation without function prototype?");
2008 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2009 NewProto->arg_type_begin(),
2010 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002011 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002012 }
2013
John McCall1d8d1cc2010-08-01 02:01:53 +00002014 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002015
Douglas Gregore53060f2009-06-25 22:08:12 +00002016 return false;
2017}
2018
Douglas Gregor5545e162009-03-24 00:38:23 +00002019/// \brief Initializes common fields of an instantiated method
2020/// declaration (New) from the corresponding fields of its template
2021/// (Tmpl).
2022///
2023/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002024bool
2025TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002026 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002027 if (InitFunctionInstantiation(New, Tmpl))
2028 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregor5545e162009-03-24 00:38:23 +00002030 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002031 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002032 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002033
2034 // FIXME: attributes
2035 // FIXME: New needs a pointer to Tmpl
2036 return false;
2037}
Douglas Gregora58861f2009-05-13 20:28:22 +00002038
2039/// \brief Instantiate the definition of the given function from its
2040/// template.
2041///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002042/// \param PointOfInstantiation the point at which the instantiation was
2043/// required. Note that this is not precisely a "point of instantiation"
2044/// for the function, but it's close.
2045///
Douglas Gregora58861f2009-05-13 20:28:22 +00002046/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002047/// function template specialization or member function of a class template
2048/// specialization.
2049///
2050/// \param Recursive if true, recursively instantiates any functions that
2051/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002052///
2053/// \param DefinitionRequired if true, then we are performing an explicit
2054/// instantiation where the body of the function is required. Complain if
2055/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002056void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002057 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002058 bool Recursive,
2059 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002060 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002061 return;
2062
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002063 // Never instantiate an explicit specialization.
2064 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2065 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002066
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002067 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002068 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002069 Stmt *Pattern = 0;
2070 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002071 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002072
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002073 if (!Pattern) {
2074 if (DefinitionRequired) {
2075 if (Function->getPrimaryTemplate())
2076 Diag(PointOfInstantiation,
2077 diag::err_explicit_instantiation_undefined_func_template)
2078 << Function->getPrimaryTemplate();
2079 else
2080 Diag(PointOfInstantiation,
2081 diag::err_explicit_instantiation_undefined_member)
2082 << 1 << Function->getDeclName() << Function->getDeclContext();
2083
2084 if (PatternDecl)
2085 Diag(PatternDecl->getLocation(),
2086 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002087 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002088 } else if (Function->getTemplateSpecializationKind()
2089 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002090 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002091 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002092 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002093
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002094 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002095 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002096
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002097 // C++0x [temp.explicit]p9:
2098 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002099 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002100 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002101 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002102 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002103 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002104 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002106 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2107 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002108 return;
2109
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002110 // If we're performing recursive template instantiation, create our own
2111 // queue of pending implicit instantiations that we will instantiate later,
2112 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002113 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002114 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002115 if (Recursive) {
2116 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002117 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregor9679caf2010-05-12 17:27:19 +00002120 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002121 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002122 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002123
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002124 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002125 // recorded, unless we're actually a member function within a local
2126 // class, in which case we need to merge our results with the parent
2127 // scope (of the enclosing function).
2128 bool MergeWithParentScope = false;
2129 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2130 MergeWithParentScope = Rec->isLocalClass();
2131
2132 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002134 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002135 // instantiation scope, and set the parameter names to those used
2136 // in the template.
2137 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2138 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2139 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2140 FunctionParam->setDeclName(PatternParam->getDeclName());
2141 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2142 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002143
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002144 // Enter the scope of this instantiation. We don't use
2145 // PushDeclContext because we don't have a scope.
2146 DeclContext *PreviousContext = CurContext;
2147 CurContext = Function;
2148
Mike Stump1eb44332009-09-09 15:08:12 +00002149 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002150 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002151
2152 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002153 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002154 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2155 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2156 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002157 }
2158
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002159 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002160 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002161
Douglas Gregor52604ab2009-09-11 21:19:12 +00002162 if (Body.isInvalid())
2163 Function->setInvalidDecl();
2164
John McCall9ae2f072010-08-23 23:25:46 +00002165 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002166 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002167
John McCall0c01d182010-03-24 05:22:00 +00002168 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2169
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002170 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002171
2172 DeclGroupRef DG(Function);
2173 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Douglas Gregor60406be2010-01-16 22:29:39 +00002175 // This class may have local implicit instantiations that need to be
2176 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002177 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002178 Scope.Exit();
2179
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002180 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002181 // Define any pending vtables.
2182 DefineUsedVTables();
2183
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002184 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002185 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002186 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002188 // Restore the set of pending vtables.
2189 VTableUses.swap(SavedVTableUses);
2190
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002191 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002192 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002193 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002194}
2195
2196/// \brief Instantiate the definition of the given variable from its
2197/// template.
2198///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002199/// \param PointOfInstantiation the point at which the instantiation was
2200/// required. Note that this is not precisely a "point of instantiation"
2201/// for the function, but it's close.
2202///
2203/// \param Var the already-instantiated declaration of a static member
2204/// variable of a class template specialization.
2205///
2206/// \param Recursive if true, recursively instantiates any functions that
2207/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002208///
2209/// \param DefinitionRequired if true, then we are performing an explicit
2210/// instantiation where an out-of-line definition of the member variable
2211/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002212void Sema::InstantiateStaticDataMemberDefinition(
2213 SourceLocation PointOfInstantiation,
2214 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002215 bool Recursive,
2216 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002217 if (Var->isInvalidDecl())
2218 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor7caa6822009-07-24 20:34:43 +00002220 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002221 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002222 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002223 assert(Def->isStaticDataMember() && "Not a static data member?");
2224 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Douglas Gregor0d035142009-10-27 18:42:08 +00002226 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002227 // We did not find an out-of-line definition of this static data member,
2228 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002229 // instantiate this definition (or provide a specialization for it) in
2230 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002231 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002232 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002233 Diag(PointOfInstantiation,
2234 diag::err_explicit_instantiation_undefined_member)
2235 << 2 << Var->getDeclName() << Var->getDeclContext();
2236 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002237 } else if (Var->getTemplateSpecializationKind()
2238 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002239 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002240 std::make_pair(Var, PointOfInstantiation));
2241 }
2242
Douglas Gregor7caa6822009-07-24 20:34:43 +00002243 return;
2244 }
2245
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002246 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002247 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002248 return;
2249
2250 // C++0x [temp.explicit]p9:
2251 // Except for inline functions, other explicit instantiation declarations
2252 // have the effect of suppressing the implicit instantiation of the entity
2253 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002254 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002255 == TSK_ExplicitInstantiationDeclaration)
2256 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Douglas Gregor7caa6822009-07-24 20:34:43 +00002258 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2259 if (Inst)
2260 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregor7caa6822009-07-24 20:34:43 +00002262 // If we're performing recursive template instantiation, create our own
2263 // queue of pending implicit instantiations that we will instantiate later,
2264 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002265 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002266 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002267 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Douglas Gregor7caa6822009-07-24 20:34:43 +00002269 // Enter the scope of this instantiation. We don't use
2270 // PushDeclContext because we don't have a scope.
2271 DeclContext *PreviousContext = CurContext;
2272 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002274 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002275 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002276 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002277 CurContext = PreviousContext;
2278
2279 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002280 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2281 assert(MSInfo && "Missing member specialization information?");
2282 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2283 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002284 DeclGroupRef DG(Var);
2285 Consumer.HandleTopLevelDecl(DG);
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor7caa6822009-07-24 20:34:43 +00002288 if (Recursive) {
2289 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002290 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002291 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregor7caa6822009-07-24 20:34:43 +00002293 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002294 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002295 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002296}
Douglas Gregor815215d2009-05-27 05:35:12 +00002297
Anders Carlsson09025312009-08-29 05:16:22 +00002298void
2299Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2300 const CXXConstructorDecl *Tmpl,
2301 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Anders Carlsson09025312009-08-29 05:16:22 +00002303 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002304 bool AnyErrors = false;
2305
Anders Carlsson09025312009-08-29 05:16:22 +00002306 // Instantiate all the initializers.
2307 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002308 InitsEnd = Tmpl->init_end();
2309 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002310 CXXBaseOrMemberInitializer *Init = *Inits;
2311
Chandler Carruth030ef472010-09-03 21:54:20 +00002312 // Only instantiate written initializers, let Sema re-construct implicit
2313 // ones.
2314 if (!Init->isWritten())
2315 continue;
2316
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002317 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002318 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002320 // Instantiate the initializer.
2321 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002322 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002323 AnyErrors = true;
2324 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002325 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002326
Anders Carlsson09025312009-08-29 05:16:22 +00002327 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002328 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002329 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002330 TemplateArgs,
2331 Init->getSourceLocation(),
2332 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002333 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002334 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002335 New->setInvalidDecl();
2336 continue;
2337 }
2338
John McCalla93c9342009-12-07 02:54:59 +00002339 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002340 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002341 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002342 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002343 Init->getRParenLoc(),
2344 New->getParent());
2345 } else if (Init->isMemberInitializer()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002346 FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2347 Init->getMemberLocation(),
2348 Init->getMember(),
2349 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002350
2351 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002352 NewArgs.size(),
2353 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002354 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002355 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002356 } else if (Init->isIndirectMemberInitializer()) {
2357 IndirectFieldDecl *IndirectMember =
2358 cast<IndirectFieldDecl>(FindInstantiatedDecl(
2359 Init->getMemberLocation(),
2360 Init->getIndirectMember(), TemplateArgs));
2361
2362 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2363 NewArgs.size(),
2364 Init->getSourceLocation(),
2365 Init->getLParenLoc(),
2366 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002367 }
2368
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002369 if (NewInit.isInvalid()) {
2370 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002371 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002372 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002373 // FIXME: It would be nice if ASTOwningVector had a release function.
2374 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Anders Carlsson09025312009-08-29 05:16:22 +00002376 NewInits.push_back((MemInitTy *)NewInit.get());
2377 }
2378 }
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Anders Carlsson09025312009-08-29 05:16:22 +00002380 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002381 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002382 /*FIXME: ColonLoc */
2383 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002384 NewInits.data(), NewInits.size(),
2385 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002386}
2387
John McCall52a575a2009-08-29 08:11:13 +00002388// TODO: this could be templated if the various decl types used the
2389// same method name.
2390static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2391 ClassTemplateDecl *Instance) {
2392 Pattern = Pattern->getCanonicalDecl();
2393
2394 do {
2395 Instance = Instance->getCanonicalDecl();
2396 if (Pattern == Instance) return true;
2397 Instance = Instance->getInstantiatedFromMemberTemplate();
2398 } while (Instance);
2399
2400 return false;
2401}
2402
Douglas Gregor0d696532009-09-28 06:34:35 +00002403static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2404 FunctionTemplateDecl *Instance) {
2405 Pattern = Pattern->getCanonicalDecl();
2406
2407 do {
2408 Instance = Instance->getCanonicalDecl();
2409 if (Pattern == Instance) return true;
2410 Instance = Instance->getInstantiatedFromMemberTemplate();
2411 } while (Instance);
2412
2413 return false;
2414}
2415
Douglas Gregored9c0f92009-10-29 00:04:11 +00002416static bool
2417isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2418 ClassTemplatePartialSpecializationDecl *Instance) {
2419 Pattern
2420 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2421 do {
2422 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2423 Instance->getCanonicalDecl());
2424 if (Pattern == Instance)
2425 return true;
2426 Instance = Instance->getInstantiatedFromMember();
2427 } while (Instance);
2428
2429 return false;
2430}
2431
John McCall52a575a2009-08-29 08:11:13 +00002432static bool isInstantiationOf(CXXRecordDecl *Pattern,
2433 CXXRecordDecl *Instance) {
2434 Pattern = Pattern->getCanonicalDecl();
2435
2436 do {
2437 Instance = Instance->getCanonicalDecl();
2438 if (Pattern == Instance) return true;
2439 Instance = Instance->getInstantiatedFromMemberClass();
2440 } while (Instance);
2441
2442 return false;
2443}
2444
2445static bool isInstantiationOf(FunctionDecl *Pattern,
2446 FunctionDecl *Instance) {
2447 Pattern = Pattern->getCanonicalDecl();
2448
2449 do {
2450 Instance = Instance->getCanonicalDecl();
2451 if (Pattern == Instance) return true;
2452 Instance = Instance->getInstantiatedFromMemberFunction();
2453 } while (Instance);
2454
2455 return false;
2456}
2457
2458static bool isInstantiationOf(EnumDecl *Pattern,
2459 EnumDecl *Instance) {
2460 Pattern = Pattern->getCanonicalDecl();
2461
2462 do {
2463 Instance = Instance->getCanonicalDecl();
2464 if (Pattern == Instance) return true;
2465 Instance = Instance->getInstantiatedFromMemberEnum();
2466 } while (Instance);
2467
2468 return false;
2469}
2470
John McCalled976492009-12-04 22:46:56 +00002471static bool isInstantiationOf(UsingShadowDecl *Pattern,
2472 UsingShadowDecl *Instance,
2473 ASTContext &C) {
2474 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2475}
2476
2477static bool isInstantiationOf(UsingDecl *Pattern,
2478 UsingDecl *Instance,
2479 ASTContext &C) {
2480 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2481}
2482
John McCall7ba107a2009-11-18 02:36:19 +00002483static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2484 UsingDecl *Instance,
2485 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002486 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002487}
2488
2489static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002490 UsingDecl *Instance,
2491 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002492 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002493}
2494
John McCall52a575a2009-08-29 08:11:13 +00002495static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2496 VarDecl *Instance) {
2497 assert(Instance->isStaticDataMember());
2498
2499 Pattern = Pattern->getCanonicalDecl();
2500
2501 do {
2502 Instance = Instance->getCanonicalDecl();
2503 if (Pattern == Instance) return true;
2504 Instance = Instance->getInstantiatedFromStaticDataMember();
2505 } while (Instance);
2506
2507 return false;
2508}
2509
John McCalled976492009-12-04 22:46:56 +00002510// Other is the prospective instantiation
2511// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002512static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002513 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002514 if (UnresolvedUsingTypenameDecl *UUD
2515 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2516 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2517 return isInstantiationOf(UUD, UD, Ctx);
2518 }
2519 }
2520
2521 if (UnresolvedUsingValueDecl *UUD
2522 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002523 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2524 return isInstantiationOf(UUD, UD, Ctx);
2525 }
2526 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002527
Anders Carlsson0d8df782009-08-29 19:37:28 +00002528 return false;
2529 }
Mike Stump1eb44332009-09-09 15:08:12 +00002530
John McCall52a575a2009-08-29 08:11:13 +00002531 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2532 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002533
John McCall52a575a2009-08-29 08:11:13 +00002534 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2535 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002536
John McCall52a575a2009-08-29 08:11:13 +00002537 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2538 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002539
Douglas Gregor7caa6822009-07-24 20:34:43 +00002540 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002541 if (Var->isStaticDataMember())
2542 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2543
2544 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2545 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002546
Douglas Gregor0d696532009-09-28 06:34:35 +00002547 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2548 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2549
Douglas Gregored9c0f92009-10-29 00:04:11 +00002550 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2551 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2552 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2553 PartialSpec);
2554
Anders Carlssond8b285f2009-09-01 04:26:58 +00002555 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2556 if (!Field->getDeclName()) {
2557 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002558 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002559 cast<FieldDecl>(D);
2560 }
2561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
John McCalled976492009-12-04 22:46:56 +00002563 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2564 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2565
2566 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2567 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2568
Douglas Gregor815215d2009-05-27 05:35:12 +00002569 return D->getDeclName() && isa<NamedDecl>(Other) &&
2570 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2571}
2572
2573template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002574static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002575 NamedDecl *D,
2576 ForwardIterator first,
2577 ForwardIterator last) {
2578 for (; first != last; ++first)
2579 if (isInstantiationOf(Ctx, D, *first))
2580 return cast<NamedDecl>(*first);
2581
2582 return 0;
2583}
2584
John McCall02cace72009-08-28 07:59:38 +00002585/// \brief Finds the instantiation of the given declaration context
2586/// within the current instantiation.
2587///
2588/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002589DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002590 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002591 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002592 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002593 return cast_or_null<DeclContext>(ID);
2594 } else return DC;
2595}
2596
Douglas Gregored961e72009-05-27 17:54:46 +00002597/// \brief Find the instantiation of the given declaration within the
2598/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002599///
2600/// This routine is intended to be used when \p D is a declaration
2601/// referenced from within a template, that needs to mapped into the
2602/// corresponding declaration within an instantiation. For example,
2603/// given:
2604///
2605/// \code
2606/// template<typename T>
2607/// struct X {
2608/// enum Kind {
2609/// KnownValue = sizeof(T)
2610/// };
2611///
2612/// bool getKind() const { return KnownValue; }
2613/// };
2614///
2615/// template struct X<int>;
2616/// \endcode
2617///
2618/// In the instantiation of X<int>::getKind(), we need to map the
2619/// EnumConstantDecl for KnownValue (which refers to
2620/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002621/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2622/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002623NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002624 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002625 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002626 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002627 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002628 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002629 // D is a local of some kind. Look into the map of local
2630 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002631 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002632 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002633
Douglas Gregore95b4092009-09-16 18:34:49 +00002634 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2635 if (!Record->isDependentContext())
2636 return D;
2637
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002638 // If the RecordDecl is actually the injected-class-name or a
2639 // "templated" declaration for a class template, class template
2640 // partial specialization, or a member class of a class template,
2641 // substitute into the injected-class-name of the class template
2642 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002643 QualType T;
2644 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2645
2646 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002647 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002648 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2649 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002650 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002651
2652 // If we call SubstType with an InjectedClassNameType here we
2653 // can end up in an infinite loop.
2654 T = Context.getTypeDeclType(Record);
2655 assert(isa<InjectedClassNameType>(T) &&
2656 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002657 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002658 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002659
2660 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002661 // Substitute into the injected-class-name to get the type
2662 // corresponding to the instantiation we want, which may also be
2663 // the current instantiation (if we're in a template
2664 // definition). This substitution should never fail, since we
2665 // know we can instantiate the injected-class-name or we
2666 // wouldn't have gotten to the injected-class-name!
2667
2668 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2669 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002670 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2671 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2672
2673 if (!T->isDependentType()) {
2674 assert(T->isRecordType() && "Instantiation must produce a record type");
2675 return T->getAs<RecordType>()->getDecl();
2676 }
2677
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002678 // We are performing "partial" template instantiation to create
2679 // the member declarations for the members of a class template
2680 // specialization. Therefore, D is actually referring to something
2681 // in the current instantiation. Look through the current
2682 // context, which contains actual instantiations, to find the
2683 // instantiation of the "current instantiation" that D refers
2684 // to.
2685 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002686 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002687 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002688 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002689 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002690 if (isInstantiationOf(ClassTemplate,
2691 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002692 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002693
2694 if (!DC->isDependentContext())
2695 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002696 }
2697
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002698 // We're performing "instantiation" of a member of the current
2699 // instantiation while we are type-checking the
2700 // definition. Compute the declaration context and return that.
2701 assert(!SawNonDependentContext &&
2702 "No dependent context while instantiating record");
2703 DeclContext *DC = computeDeclContext(T);
2704 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002705 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002706 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002707 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002708
Douglas Gregore95b4092009-09-16 18:34:49 +00002709 // Fall through to deal with other dependent record types (e.g.,
2710 // anonymous unions in class templates).
2711 }
John McCall52a575a2009-08-29 08:11:13 +00002712
Douglas Gregore95b4092009-09-16 18:34:49 +00002713 if (!ParentDC->isDependentContext())
2714 return D;
2715
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002716 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002717 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002718 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor815215d2009-05-27 05:35:12 +00002720 if (ParentDC != D->getDeclContext()) {
2721 // We performed some kind of instantiation in the parent context,
2722 // so now we need to look into the instantiated parent context to
2723 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002724
John McCall3cb0ebd2010-03-10 03:28:59 +00002725 // If our context used to be dependent, we may need to instantiate
2726 // it before performing lookup into that context.
2727 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002728 if (!Spec->isDependentContext()) {
2729 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002730 const RecordType *Tag = T->getAs<RecordType>();
2731 assert(Tag && "type of non-dependent record is not a RecordType");
2732 if (!Tag->isBeingDefined() &&
2733 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2734 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002735
2736 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002737 }
2738 }
2739
Douglas Gregor815215d2009-05-27 05:35:12 +00002740 NamedDecl *Result = 0;
2741 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002742 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002743 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2744 } else {
2745 // Since we don't have a name for the entity we're looking for,
2746 // our only option is to walk through all of the declarations to
2747 // find that name. This will occur in a few cases:
2748 //
2749 // - anonymous struct/union within a template
2750 // - unnamed class/struct/union/enum within a template
2751 //
2752 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002753 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002754 ParentDC->decls_begin(),
2755 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002756 }
Mike Stump1eb44332009-09-09 15:08:12 +00002757
John McCall9f54ad42009-12-10 09:41:52 +00002758 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002759 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2760 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002761 && "Unable to find instantiation of declaration!");
2762
Douglas Gregor815215d2009-05-27 05:35:12 +00002763 D = Result;
2764 }
2765
Douglas Gregor815215d2009-05-27 05:35:12 +00002766 return D;
2767}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002768
Mike Stump1eb44332009-09-09 15:08:12 +00002769/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002770/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002771void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002772 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002773 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002774 PendingImplicitInstantiation Inst;
2775
2776 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002777 Inst = PendingInstantiations.front();
2778 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002779 } else {
2780 Inst = PendingLocalImplicitInstantiations.front();
2781 PendingLocalImplicitInstantiations.pop_front();
2782 }
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Douglas Gregor7caa6822009-07-24 20:34:43 +00002784 // Instantiate function definitions
2785 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002786 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2787 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002788 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2789 TSK_ExplicitInstantiationDefinition;
2790 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2791 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002792 continue;
2793 }
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Douglas Gregor7caa6822009-07-24 20:34:43 +00002795 // Instantiate static data member definitions.
2796 VarDecl *Var = cast<VarDecl>(Inst.first);
2797 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002798
Chandler Carruth291b4412010-02-13 10:17:50 +00002799 // Don't try to instantiate declarations if the most recent redeclaration
2800 // is invalid.
2801 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2802 continue;
2803
2804 // Check if the most recent declaration has changed the specialization kind
2805 // and removed the need for implicit instantiation.
2806 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2807 case TSK_Undeclared:
2808 assert(false && "Cannot instantitiate an undeclared specialization.");
2809 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002810 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002811 continue; // No longer need to instantiate this type.
2812 case TSK_ExplicitInstantiationDefinition:
2813 // We only need an instantiation if the pending instantiation *is* the
2814 // explicit instantiation.
2815 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002816 case TSK_ImplicitInstantiation:
2817 break;
2818 }
2819
John McCallf312b1e2010-08-26 23:41:50 +00002820 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2821 "instantiating static data member "
2822 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Chandler Carruth58e390e2010-08-25 08:27:02 +00002824 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2825 TSK_ExplicitInstantiationDefinition;
2826 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2827 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002828 }
2829}
John McCall0c01d182010-03-24 05:22:00 +00002830
2831void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2832 const MultiLevelTemplateArgumentList &TemplateArgs) {
2833 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2834 E = Pattern->ddiag_end(); I != E; ++I) {
2835 DependentDiagnostic *DD = *I;
2836
2837 switch (DD->getKind()) {
2838 case DependentDiagnostic::Access:
2839 HandleDependentAccessCheck(*DD, TemplateArgs);
2840 break;
2841 }
2842 }
2843}