blob: 615c6f9456757ed19c6eae818b53437f9feec258 [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//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000019#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021
22using namespace clang;
23
24namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000025 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000026 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000027 Sema &SemaRef;
28 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000029 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Anders Carlssond8fe2d52009-11-07 06:07:58 +000031 void InstantiateAttrs(Decl *Tmpl, Decl *New);
32
Douglas Gregor8dbc2692009-03-17 21:15:40 +000033 public:
34 typedef Sema::OwningExprResult OwningExprResult;
35
36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000037 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000038 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000039
Mike Stump390b4cc2009-05-16 07:39:55 +000040 // FIXME: Once we get closer to completion, replace these manually-written
41 // declarations with automatically-generated ones from
42 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000043 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000045 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000046 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitFieldDecl(FieldDecl *D);
48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
49 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000050 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000051 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000052 Decl *VisitFunctionDecl(FunctionDecl *D,
53 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000054 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000055 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000057 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000058 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000059 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000060 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000061 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000062 Decl *VisitClassTemplatePartialSpecializationDecl(
63 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000064 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000066 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000067 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000068 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000069 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
70 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000071
Douglas Gregor8dbc2692009-03-17 21:15:40 +000072 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000073 Decl *VisitDecl(Decl *D) {
74 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
75 Diagnostic::Error,
76 "cannot instantiate %0 yet");
77 SemaRef.Diag(D->getLocation(), DiagID)
78 << D->getDeclKindName();
79
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080 return 0;
81 }
Douglas Gregor5545e162009-03-24 00:38:23 +000082
John McCallfd810b12009-08-14 02:03:10 +000083 const LangOptions &getLangOptions() {
84 return SemaRef.getLangOptions();
85 }
86
Douglas Gregor5545e162009-03-24 00:38:23 +000087 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000088 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000089 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000090 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000091 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000092
93 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000094 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000095
96 bool InstantiateClassTemplatePartialSpecialization(
97 ClassTemplateDecl *ClassTemplate,
98 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000099 };
100}
101
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000102// FIXME: Is this too simple?
103void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
104 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
105 TmplAttr = TmplAttr->getNext()) {
106
107 // FIXME: Is cloning correct for all attributes?
108 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
109
110 New->addAttr(NewAttr);
111 }
112}
113
Douglas Gregor4f722be2009-03-25 15:45:12 +0000114Decl *
115TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
116 assert(false && "Translation units cannot be instantiated");
117 return D;
118}
119
120Decl *
121TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
122 assert(false && "Namespaces cannot be instantiated");
123 return D;
124}
125
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000126Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
127 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000128 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
129 if (DI->getType()->isDependentType()) {
130 DI = SemaRef.SubstType(DI, TemplateArgs,
131 D->getLocation(), D->getDeclName());
132 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000134 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000135 }
136 }
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 // Create the new typedef
139 TypedefDecl *Typedef
140 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000141 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 if (Invalid)
143 Typedef->setInvalidDecl();
144
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000145 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 return Typedef;
148}
149
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000150Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000151 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000152 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
153 TemplateArgs,
154 D->getTypeSpecStartLoc(),
155 D->getDeclName());
156 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 return 0;
158
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000159 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000160 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
161 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000162 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000163 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000164 Var->setThreadSpecified(D->isThreadSpecified());
165 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
166 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000167
168 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000169 // out-of-line, the instantiation will have the same lexical
170 // context (which will be a namespace scope) as the template.
171 if (D->isOutOfLine())
172 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Mike Stump390b4cc2009-05-16 07:39:55 +0000174 // FIXME: In theory, we could have a previous declaration for variables that
175 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000176 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000177 // FIXME: having to fake up a LookupResult is dumb.
178 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
179 Sema::LookupOrdinaryName);
180 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregor7caa6822009-07-24 20:34:43 +0000182 if (D->isOutOfLine()) {
183 D->getLexicalDeclContext()->addDecl(Var);
184 Owner->makeDeclVisibleInContext(Var);
185 } else {
186 Owner->addDecl(Var);
187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000189 // Link instantiations of static data members back to the template from
190 // which they were instantiated.
191 if (Var->isStaticDataMember())
192 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000193 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000194
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 if (D->getInit()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000196 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000197 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000198 if (Init.isInvalid())
199 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000200 else if (!D->getType()->isDependentType() &&
201 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000202 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000203 // If neither the declaration's type nor its initializer are dependent,
204 // we don't want to redo all the checking, especially since the
205 // initializer might have been wrapped by a CXXConstructExpr since we did
206 // it the first time.
Anders Carlssona244dc32009-11-24 16:52:50 +0000207 Var->setType(D->getType());
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000208 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
209 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000210 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000211 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000212 // Do we even need these comma locations?
213 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
214 if (PLE->getNumExprs() > 0) {
215 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
216 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
217 Expr *E = PLE->getExpr(I)->Retain();
218 FakeCommaLocs.push_back(
219 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
220 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000221 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Douglas Gregor83ddad32009-08-26 21:14:46 +0000224 // Add the direct initializer to the declaration.
225 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000226 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000227 Sema::MultiExprArg(SemaRef,
228 (void**)PLE->getExprs(),
229 PLE->getNumExprs()),
230 FakeCommaLocs.data(),
231 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Douglas Gregor83ddad32009-08-26 21:14:46 +0000233 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
234 // we've explicitly retained all of its subexpressions already.
235 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000236 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000237 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000238 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
239 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000240
241 return Var;
242}
243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
245 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000246 DeclaratorInfo *DI = D->getDeclaratorInfo();
247 if (DI->getType()->isDependentType()) {
248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
251 DI = D->getDeclaratorInfo();
252 Invalid = true;
253 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000254 // C++ [temp.arg.type]p3:
255 // If a declaration acquires a function type through a type
256 // dependent on a template-parameter and this causes a
257 // declaration that does not use the syntactic form of a
258 // function declarator to have function type, the program is
259 // ill-formed.
260 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000261 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000262 Invalid = true;
263 }
264 }
265
266 Expr *BitWidth = D->getBitWidth();
267 if (Invalid)
268 BitWidth = 0;
269 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000270 // The bit-width expression is not potentially evaluated.
271 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000273 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000274 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000275 if (InstantiatedBitWidth.isInvalid()) {
276 Invalid = true;
277 BitWidth = 0;
278 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000279 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000280 }
281
John McCall07fb6be2009-10-22 23:33:21 +0000282 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
283 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000285 D->getLocation(),
286 D->isMutable(),
287 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000288 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000289 D->getAccess(),
290 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000291 if (!Field) {
292 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000293 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000294 }
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000296 InstantiateAttrs(D, Field);
297
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000298 if (Invalid)
299 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000301 if (!Field->getDeclName()) {
302 // Keep track of where this decl came from.
303 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000304 }
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000306 Field->setImplicit(D->isImplicit());
307 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000308
309 return Field;
310}
311
John McCall02cace72009-08-28 07:59:38 +0000312Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
313 FriendDecl::FriendUnion FU;
314
315 // Handle friend type expressions by simply substituting template
316 // parameters into the pattern type.
317 if (Type *Ty = D->getFriendType()) {
318 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
319 D->getLocation(), DeclarationName());
320 if (T.isNull()) return 0;
321
322 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
323 FU = T.getTypePtr();
324
325 // Handle everything else by appropriate substitution.
326 } else {
327 NamedDecl *ND = D->getFriendDecl();
328 assert(ND && "friend decl must be a decl or a type!");
329
Douglas Gregora735b202009-10-13 14:39:41 +0000330 // FIXME: We have a problem here, because the nested call to Visit(ND)
331 // will inject the thing that the friend references into the current
332 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000333 Decl *NewND = Visit(ND);
334 if (!NewND) return 0;
335
336 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
John McCall02cace72009-08-28 07:59:38 +0000339 FriendDecl *FD =
340 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
341 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000342 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000343 Owner->addDecl(FD);
344 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000345}
346
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000347Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
348 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Douglas Gregorac7610d2009-06-22 20:57:11 +0000350 // The expression in a static assertion is not potentially evaluated.
351 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000353 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000354 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355 if (InstantiatedAssertExpr.isInvalid())
356 return 0;
357
Douglas Gregor43d9d922009-08-08 01:41:12 +0000358 OwningExprResult Message(SemaRef, D->getMessage());
359 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000360 Decl *StaticAssert
361 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000362 move(InstantiatedAssertExpr),
363 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000364 return StaticAssert;
365}
366
367Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000368 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000369 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000370 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000372 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000373 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000374 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 Enum->startDefinition();
376
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000377 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378
379 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000380 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
381 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382 EC != ECEnd; ++EC) {
383 // The specified value for the enumerator.
384 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000385 if (Expr *UninstValue = EC->getInitExpr()) {
386 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000387 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000388 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000389
John McCallce3ff2b2009-08-25 22:02:44 +0000390 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000391 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000392
393 // Drop the initial value and continue.
394 bool isInvalid = false;
395 if (Value.isInvalid()) {
396 Value = SemaRef.Owned((Expr *)0);
397 isInvalid = true;
398 }
399
Mike Stump1eb44332009-09-09 15:08:12 +0000400 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
402 EC->getLocation(), EC->getIdentifier(),
403 move(Value));
404
405 if (isInvalid) {
406 if (EnumConst)
407 EnumConst->setInvalidDecl();
408 Enum->setInvalidDecl();
409 }
410
411 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000412 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000413 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000414 LastEnumConst = EnumConst;
415 }
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000418 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000419 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000420 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
421 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000422 &Enumerators[0], Enumerators.size(),
423 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000424
425 return Enum;
426}
427
Douglas Gregor6477b692009-03-25 15:04:13 +0000428Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
429 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
430 return 0;
431}
432
Douglas Gregored9c0f92009-10-29 00:04:11 +0000433namespace {
434 class SortDeclByLocation {
435 SourceManager &SourceMgr;
436
437 public:
438 explicit SortDeclByLocation(SourceManager &SourceMgr)
439 : SourceMgr(SourceMgr) { }
440
441 bool operator()(const Decl *X, const Decl *Y) const {
442 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
443 Y->getLocation());
444 }
445 };
446}
447
John McCalle29ba202009-08-20 01:44:21 +0000448Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000449 // Create a local instantiation scope for this class template, which
450 // will contain the instantiations of the template parameters.
451 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000452 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000453 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000454 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000455 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000456
457 CXXRecordDecl *Pattern = D->getTemplatedDecl();
458 CXXRecordDecl *RecordInst
459 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
460 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000461 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
462 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000463
464 ClassTemplateDecl *Inst
465 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
466 D->getIdentifier(), InstParams, RecordInst, 0);
467 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000468 if (D->getFriendObjectKind())
469 Inst->setObjectOfFriendDecl(true);
470 else
471 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000472 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000473
474 // Trigger creation of the type for the instantiation.
475 SemaRef.Context.getTypeDeclType(RecordInst);
476
Douglas Gregor259571e2009-10-30 22:42:42 +0000477 // Finish handling of friends.
478 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000479 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000480 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000481
John McCalle29ba202009-08-20 01:44:21 +0000482 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000483
484 // First, we sort the partial specializations by location, so
485 // that we instantiate them in the order they were declared.
486 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
487 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
488 P = D->getPartialSpecializations().begin(),
489 PEnd = D->getPartialSpecializations().end();
490 P != PEnd; ++P)
491 PartialSpecs.push_back(&*P);
492 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
493 SortDeclByLocation(SemaRef.SourceMgr));
494
495 // Instantiate all of the partial specializations of this member class
496 // template.
497 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
498 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
499
John McCalle29ba202009-08-20 01:44:21 +0000500 return Inst;
501}
502
Douglas Gregord60e1052009-08-27 16:57:43 +0000503Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000504TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
505 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000506 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
507
508 // Lookup the already-instantiated declaration in the instantiation
509 // of the class template and return that.
510 DeclContext::lookup_result Found
511 = Owner->lookup(ClassTemplate->getDeclName());
512 if (Found.first == Found.second)
513 return 0;
514
515 ClassTemplateDecl *InstClassTemplate
516 = dyn_cast<ClassTemplateDecl>(*Found.first);
517 if (!InstClassTemplate)
518 return 0;
519
520 Decl *DCanon = D->getCanonicalDecl();
521 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
522 P = InstClassTemplate->getPartialSpecializations().begin(),
523 PEnd = InstClassTemplate->getPartialSpecializations().end();
524 P != PEnd; ++P) {
525 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
526 return &*P;
527 }
528
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000529 return 0;
530}
531
532Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000533TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000534 // Create a local instantiation scope for this function template, which
535 // will contain the instantiations of the template parameters and then get
536 // merged with the local instantiation scope for the function template
537 // itself.
538 Sema::LocalInstantiationScope Scope(SemaRef);
539
Douglas Gregord60e1052009-08-27 16:57:43 +0000540 TemplateParameterList *TempParams = D->getTemplateParameters();
541 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000542 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000543 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000544
Douglas Gregora735b202009-10-13 14:39:41 +0000545 FunctionDecl *Instantiated = 0;
546 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
547 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
548 InstParams));
549 else
550 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
551 D->getTemplatedDecl(),
552 InstParams));
553
554 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000555 return 0;
556
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000558 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000559 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000560 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000561 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000562 assert(InstTemplate &&
563 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
564 if (!InstTemplate->getInstantiatedFromMemberTemplate())
565 InstTemplate->setInstantiatedFromMemberTemplate(D);
566
567 // Add non-friends into the owner.
568 if (!InstTemplate->getFriendObjectKind())
569 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000570 return InstTemplate;
571}
572
Douglas Gregord475b8d2009-03-25 21:17:03 +0000573Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
574 CXXRecordDecl *PrevDecl = 0;
575 if (D->isInjectedClassName())
576 PrevDecl = cast<CXXRecordDecl>(Owner);
577
578 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000579 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000580 D->getLocation(), D->getIdentifier(),
581 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000582 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000583 // FIXME: Check against AS_none is an ugly hack to work around the issue that
584 // the tag decls introduced by friend class declarations don't have an access
585 // specifier. Remove once this area of the code gets sorted out.
586 if (D->getAccess() != AS_none)
587 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000588 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000589 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000590
John McCall02cace72009-08-28 07:59:38 +0000591 // If the original function was part of a friend declaration,
592 // inherit its namespace state.
593 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
594 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
595
Anders Carlssond8b285f2009-09-01 04:26:58 +0000596 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
597
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000598 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000599 return Record;
600}
601
John McCall02cace72009-08-28 07:59:38 +0000602/// Normal class members are of more specific types and therefore
603/// don't make it here. This function serves two purposes:
604/// 1) instantiating function templates
605/// 2) substituting friend declarations
606/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000607 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
608 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000609 // Check whether there is already a function template specialization for
610 // this declaration.
611 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
612 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000613 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000614 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000615 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000616 TemplateArgs.getInnermost().getFlatArgumentList(),
617 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000618 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000619
620 FunctionTemplateSpecializationInfo *Info
621 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000622 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Douglas Gregor127102b2009-06-29 20:59:39 +0000624 // If we already have a function template specialization, return it.
625 if (Info)
626 return Info->Function;
627 }
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Douglas Gregor550d9b22009-10-31 17:21:17 +0000629 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregore53060f2009-06-25 22:08:12 +0000631 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000632 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000633 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000634 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000635
Douglas Gregore53060f2009-06-25 22:08:12 +0000636 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000637 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
638 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000639 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000640 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000641 D->getDeclName(), T, D->getDeclaratorInfo(),
642 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000643 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000644 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Douglas Gregore53060f2009-06-25 22:08:12 +0000646 // Attach the parameters
647 for (unsigned P = 0; P < Params.size(); ++P)
648 Params[P]->setOwningFunction(Function);
649 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000650
Douglas Gregora735b202009-10-13 14:39:41 +0000651 if (TemplateParams) {
652 // Our resulting instantiation is actually a function template, since we
653 // are substituting only the outer template parameters. For example, given
654 //
655 // template<typename T>
656 // struct X {
657 // template<typename U> friend void f(T, U);
658 // };
659 //
660 // X<int> x;
661 //
662 // We are instantiating the friend function template "f" within X<int>,
663 // which means substituting int for T, but leaving "f" as a friend function
664 // template.
665 // Build the function template itself.
666 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
667 Function->getLocation(),
668 Function->getDeclName(),
669 TemplateParams, Function);
670 Function->setDescribedFunctionTemplate(FunctionTemplate);
671 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000672 } else if (FunctionTemplate) {
673 // Record this function template specialization.
674 Function->setFunctionTemplateSpecialization(SemaRef.Context,
675 FunctionTemplate,
676 &TemplateArgs.getInnermost(),
677 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000678 }
Douglas Gregora735b202009-10-13 14:39:41 +0000679
Douglas Gregore53060f2009-06-25 22:08:12 +0000680 if (InitFunctionInstantiation(Function, D))
681 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Douglas Gregore53060f2009-06-25 22:08:12 +0000683 bool Redeclaration = false;
684 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000685
John McCall68263142009-11-18 22:49:29 +0000686 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
687 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
688
Douglas Gregora735b202009-10-13 14:39:41 +0000689 if (TemplateParams || !FunctionTemplate) {
690 // Look only into the namespace where the friend would be declared to
691 // find a previous declaration. This is the innermost enclosing namespace,
692 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000693 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000694
Douglas Gregora735b202009-10-13 14:39:41 +0000695 // In C++, the previous declaration we find might be a tag type
696 // (class or enum). In this case, the new declaration will hide the
697 // tag type. Note that this does does not apply if we're declaring a
698 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000699 if (Previous.isSingleTagDecl())
700 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000701 }
702
John McCall68263142009-11-18 22:49:29 +0000703 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000704 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000705
Douglas Gregora735b202009-10-13 14:39:41 +0000706 // If the original function was part of a friend declaration,
707 // inherit its namespace state and add it to the owner.
708 NamedDecl *FromFriendD
709 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
710 if (FromFriendD->getFriendObjectKind()) {
711 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000712 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000713 if (TemplateParams) {
714 ToFriendD = cast<NamedDecl>(FunctionTemplate);
715 PrevDecl = FunctionTemplate->getPreviousDeclaration();
716 } else {
717 ToFriendD = Function;
718 PrevDecl = Function->getPreviousDeclaration();
719 }
720 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
721 if (!Owner->isDependentContext() && !PrevDecl)
722 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
723
724 if (!TemplateParams)
725 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
726 }
727
Douglas Gregore53060f2009-06-25 22:08:12 +0000728 return Function;
729}
730
Douglas Gregord60e1052009-08-27 16:57:43 +0000731Decl *
732TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
733 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000734 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
735 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000736 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000737 // We are creating a function template specialization from a function
738 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000739 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000740 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000741 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000742 TemplateArgs.getInnermost().getFlatArgumentList(),
743 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000744 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
746 FunctionTemplateSpecializationInfo *Info
747 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000748 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Douglas Gregor6b906862009-08-21 00:16:32 +0000750 // If we already have a function template specialization, return it.
751 if (Info)
752 return Info->Function;
753 }
754
Douglas Gregor550d9b22009-10-31 17:21:17 +0000755 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000756
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000757 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000758 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000759 if (T.isNull())
760 return 0;
761
762 // Build the instantiated method declaration.
763 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000764 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregordec06662009-08-21 18:42:58 +0000766 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000767 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000768 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
769 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
770 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000771 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
772 Constructor->getLocation(),
773 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000774 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000775 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000776 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000777 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
778 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
779 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
780 SemaRef.Context.getCanonicalType(ClassTy));
781 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
782 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000783 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000784 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000785 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000786 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000787 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000788 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
789 ConvTy);
790 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
791 Conversion->getLocation(), Name,
792 T, Conversion->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000793 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000794 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000795 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000796 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000797 D->getDeclName(), T, D->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000798 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000799 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000800
Douglas Gregord60e1052009-08-27 16:57:43 +0000801 if (TemplateParams) {
802 // Our resulting instantiation is actually a function template, since we
803 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000804 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000805 // template<typename T>
806 // struct X {
807 // template<typename U> void f(T, U);
808 // };
809 //
810 // X<int> x;
811 //
812 // We are instantiating the member template "f" within X<int>, which means
813 // substituting int for T, but leaving "f" as a member function template.
814 // Build the function template itself.
815 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
816 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000817 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000818 TemplateParams, Method);
819 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000820 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000821 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000822 } else if (FunctionTemplate) {
823 // Record this function template specialization.
824 Method->setFunctionTemplateSpecialization(SemaRef.Context,
825 FunctionTemplate,
826 &TemplateArgs.getInnermost(),
827 InsertPos);
828 } else {
829 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000830 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000831 }
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000834 // out-of-line, the instantiation will have the same lexical
835 // context (which will be a namespace scope) as the template.
836 if (D->isOutOfLine())
837 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor5545e162009-03-24 00:38:23 +0000839 // Attach the parameters
840 for (unsigned P = 0; P < Params.size(); ++P)
841 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000842 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000843
844 if (InitMethodInstantiation(Method, D))
845 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000846
John McCall68263142009-11-18 22:49:29 +0000847 LookupResult Previous(SemaRef, Name, SourceLocation(),
848 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000851 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregordec06662009-08-21 18:42:58 +0000853 // In C++, the previous declaration we find might be a tag type
854 // (class or enum). In this case, the new declaration will hide the
855 // tag type. Note that this does does not apply if we're declaring a
856 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000857 if (Previous.isSingleTagDecl())
858 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000859 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000860
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000861 bool Redeclaration = false;
862 bool OverloadableAttrRequired = false;
John McCall68263142009-11-18 22:49:29 +0000863 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000864 /*FIXME:*/OverloadableAttrRequired);
865
Douglas Gregor4ba31362009-12-01 17:24:26 +0000866 if (D->isPure())
867 SemaRef.CheckPureMethod(Method, SourceRange());
868
John McCall68263142009-11-18 22:49:29 +0000869 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000870 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000871 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Sebastian Redla165da02009-11-18 21:51:29 +0000873 SemaRef.AddOverriddenMethods(Record, Method);
874
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000875 return Method;
876}
877
Douglas Gregor615c5d42009-03-24 16:43:20 +0000878Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000879 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000880}
881
Douglas Gregor03b2b072009-03-24 00:15:49 +0000882Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000883 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000884}
885
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000886Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000887 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000888}
889
Douglas Gregor6477b692009-03-25 15:04:13 +0000890ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000891 QualType T;
892 DeclaratorInfo *DI = D->getDeclaratorInfo();
893 if (DI) {
894 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
895 D->getDeclName());
896 if (DI) T = DI->getType();
897 } else {
898 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
899 D->getDeclName());
900 DI = 0;
901 }
902
903 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000904 return 0;
905
John McCall58e46772009-10-23 21:48:59 +0000906 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000907
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000908 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000909 ParmVarDecl *Param
910 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
911 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000912
Anders Carlsson9351c172009-08-25 03:18:48 +0000913 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000914 if (D->hasUninstantiatedDefaultArg())
915 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000916 else if (Expr *Arg = D->getDefaultArg())
917 Param->setUninstantiatedDefaultArg(Arg);
918
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000919 // Note: we don't try to instantiate function parameters until after
920 // we've instantiated the function's type. Therefore, we don't have
921 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000922 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000923 return Param;
924}
925
John McCalle29ba202009-08-20 01:44:21 +0000926Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
927 TemplateTypeParmDecl *D) {
928 // TODO: don't always clone when decls are refcounted.
929 const Type* T = D->getTypeForDecl();
930 assert(T->isTemplateTypeParmType());
931 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCalle29ba202009-08-20 01:44:21 +0000933 TemplateTypeParmDecl *Inst =
934 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000935 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000936 TTPT->getName(),
937 D->wasDeclaredWithTypename(),
938 D->isParameterPack());
939
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000940 if (D->hasDefaultArgument())
941 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000942
Douglas Gregor550d9b22009-10-31 17:21:17 +0000943 // Introduce this template parameter's instantiation into the instantiation
944 // scope.
945 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
946
John McCalle29ba202009-08-20 01:44:21 +0000947 return Inst;
948}
949
Douglas Gregor33642df2009-10-23 23:25:44 +0000950Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
951 NonTypeTemplateParmDecl *D) {
952 // Substitute into the type of the non-type template parameter.
953 QualType T;
954 DeclaratorInfo *DI = D->getDeclaratorInfo();
955 if (DI) {
956 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
957 D->getDeclName());
958 if (DI) T = DI->getType();
959 } else {
960 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
961 D->getDeclName());
962 DI = 0;
963 }
964 if (T.isNull())
965 return 0;
966
967 // Check that this type is acceptable for a non-type template parameter.
968 bool Invalid = false;
969 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
970 if (T.isNull()) {
971 T = SemaRef.Context.IntTy;
972 Invalid = true;
973 }
974
975 NonTypeTemplateParmDecl *Param
976 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
977 D->getDepth() - 1, D->getPosition(),
978 D->getIdentifier(), T, DI);
979 if (Invalid)
980 Param->setInvalidDecl();
981
982 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000983
984 // Introduce this template parameter's instantiation into the instantiation
985 // scope.
986 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000987 return Param;
988}
989
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000990Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000991TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
992 TemplateTemplateParmDecl *D) {
993 // Instantiate the template parameter list of the template template parameter.
994 TemplateParameterList *TempParams = D->getTemplateParameters();
995 TemplateParameterList *InstParams;
996 {
997 // Perform the actual substitution of template parameters within a new,
998 // local instantiation scope.
999 Sema::LocalInstantiationScope Scope(SemaRef);
1000 InstParams = SubstTemplateParams(TempParams);
1001 if (!InstParams)
1002 return NULL;
1003 }
1004
1005 // Build the template template parameter.
1006 TemplateTemplateParmDecl *Param
1007 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1008 D->getDepth() - 1, D->getPosition(),
1009 D->getIdentifier(), InstParams);
1010 Param->setDefaultArgument(D->getDefaultArgument());
1011
1012 // Introduce this template parameter's instantiation into the instantiation
1013 // scope.
1014 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1015
1016 return Param;
1017}
1018
Douglas Gregor48c32a72009-11-17 06:07:40 +00001019Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1020 // Using directives are never dependent, so they require no explicit
1021
1022 UsingDirectiveDecl *Inst
1023 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1024 D->getNamespaceKeyLocation(),
1025 D->getQualifierRange(), D->getQualifier(),
1026 D->getIdentLocation(),
1027 D->getNominatedNamespace(),
1028 D->getCommonAncestor());
1029 Owner->addDecl(Inst);
1030 return Inst;
1031}
1032
John McCall7ba107a2009-11-18 02:36:19 +00001033Decl * TemplateDeclInstantiator
1034 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001035 NestedNameSpecifier *NNS =
1036 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1037 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001038 TemplateArgs);
1039 if (!NNS)
1040 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001042 CXXScopeSpec SS;
1043 SS.setRange(D->getTargetNestedNameRange());
1044 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
1046 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001047 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001048 D->getUsingLoc(), SS, D->getLocation(),
1049 D->getDeclName(), 0,
1050 /*instantiation*/ true,
1051 /*typename*/ true, D->getTypenameLoc());
1052 if (UD)
1053 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1054 D);
1055 return UD;
1056}
1057
1058Decl * TemplateDeclInstantiator
1059 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1060 NestedNameSpecifier *NNS =
1061 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1062 D->getTargetNestedNameRange(),
1063 TemplateArgs);
1064 if (!NNS)
1065 return 0;
1066
1067 CXXScopeSpec SS;
1068 SS.setRange(D->getTargetNestedNameRange());
1069 SS.setScopeRep(NNS);
1070
1071 NamedDecl *UD =
1072 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1073 D->getUsingLoc(), SS, D->getLocation(),
1074 D->getDeclName(), 0,
1075 /*instantiation*/ true,
1076 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001077 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +00001078 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +00001079 D);
1080 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001081}
1082
John McCallce3ff2b2009-08-25 22:02:44 +00001083Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001084 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001085 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001086 return Instantiator.Visit(D);
1087}
1088
John McCalle29ba202009-08-20 01:44:21 +00001089/// \brief Instantiates a nested template parameter list in the current
1090/// instantiation context.
1091///
1092/// \param L The parameter list to instantiate
1093///
1094/// \returns NULL if there was an error
1095TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001096TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001097 // Get errors for all the parameters before bailing out.
1098 bool Invalid = false;
1099
1100 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001101 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001102 ParamVector Params;
1103 Params.reserve(N);
1104 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1105 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001106 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001107 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001108 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001109 }
1110
1111 // Clean up if we had an error.
1112 if (Invalid) {
1113 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1114 PI != PE; ++PI)
1115 if (*PI)
1116 (*PI)->Destroy(SemaRef.Context);
1117 return NULL;
1118 }
1119
1120 TemplateParameterList *InstL
1121 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1122 L->getLAngleLoc(), &Params.front(), N,
1123 L->getRAngleLoc());
1124 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001125}
John McCalle29ba202009-08-20 01:44:21 +00001126
Douglas Gregored9c0f92009-10-29 00:04:11 +00001127/// \brief Instantiate the declaration of a class template partial
1128/// specialization.
1129///
1130/// \param ClassTemplate the (instantiated) class template that is partially
1131// specialized by the instantiation of \p PartialSpec.
1132///
1133/// \param PartialSpec the (uninstantiated) class template partial
1134/// specialization that we are instantiating.
1135///
1136/// \returns true if there was an error, false otherwise.
1137bool
1138TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1139 ClassTemplateDecl *ClassTemplate,
1140 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001141 // Create a local instantiation scope for this class template partial
1142 // specialization, which will contain the instantiations of the template
1143 // parameters.
1144 Sema::LocalInstantiationScope Scope(SemaRef);
1145
Douglas Gregored9c0f92009-10-29 00:04:11 +00001146 // Substitute into the template parameters of the class template partial
1147 // specialization.
1148 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1149 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1150 if (!InstParams)
1151 return true;
1152
1153 // Substitute into the template arguments of the class template partial
1154 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001155 const TemplateArgumentLoc *PartialSpecTemplateArgs
1156 = PartialSpec->getTemplateArgsAsWritten();
1157 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1158
John McCalld5532b62009-11-23 01:53:49 +00001159 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001160 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001161 TemplateArgumentLoc Loc;
1162 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001163 return true;
John McCalld5532b62009-11-23 01:53:49 +00001164 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001165 }
1166
1167
1168 // Check that the template argument list is well-formed for this
1169 // class template.
1170 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1171 InstTemplateArgs.size());
1172 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1173 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001174 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001175 false,
1176 Converted))
1177 return true;
1178
1179 // Figure out where to insert this class template partial specialization
1180 // in the member template's set of class template partial specializations.
1181 llvm::FoldingSetNodeID ID;
1182 ClassTemplatePartialSpecializationDecl::Profile(ID,
1183 Converted.getFlatArguments(),
1184 Converted.flatSize(),
1185 SemaRef.Context);
1186 void *InsertPos = 0;
1187 ClassTemplateSpecializationDecl *PrevDecl
1188 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1189 InsertPos);
1190
1191 // Build the canonical type that describes the converted template
1192 // arguments of the class template partial specialization.
1193 QualType CanonType
1194 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1195 Converted.getFlatArguments(),
1196 Converted.flatSize());
1197
1198 // Build the fully-sugared type for this class template
1199 // specialization as the user wrote in the specialization
1200 // itself. This means that we'll pretty-print the type retrieved
1201 // from the specialization's declaration the way that the user
1202 // actually wrote the specialization, rather than formatting the
1203 // name based on the "canonical" representation used to store the
1204 // template arguments in the specialization.
1205 QualType WrittenTy
1206 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001207 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001208 CanonType);
1209
1210 if (PrevDecl) {
1211 // We've already seen a partial specialization with the same template
1212 // parameters and template arguments. This can happen, for example, when
1213 // substituting the outer template arguments ends up causing two
1214 // class template partial specializations of a member class template
1215 // to have identical forms, e.g.,
1216 //
1217 // template<typename T, typename U>
1218 // struct Outer {
1219 // template<typename X, typename Y> struct Inner;
1220 // template<typename Y> struct Inner<T, Y>;
1221 // template<typename Y> struct Inner<U, Y>;
1222 // };
1223 //
1224 // Outer<int, int> outer; // error: the partial specializations of Inner
1225 // // have the same signature.
1226 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1227 << WrittenTy;
1228 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1229 << SemaRef.Context.getTypeDeclType(PrevDecl);
1230 return true;
1231 }
1232
1233
1234 // Create the class template partial specialization declaration.
1235 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1236 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1237 PartialSpec->getLocation(),
1238 InstParams,
1239 ClassTemplate,
1240 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001241 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001242 0);
1243 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1244 InstPartialSpec->setTypeAsWritten(WrittenTy);
1245
1246 // Add this partial specialization to the set of class template partial
1247 // specializations.
1248 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1249 InsertPos);
1250 return false;
1251}
1252
John McCallce3ff2b2009-08-25 22:02:44 +00001253/// \brief Does substitution on the type of the given function, including
1254/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001255///
John McCallce3ff2b2009-08-25 22:02:44 +00001256/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001257///
1258/// \param Params the instantiated parameter declarations
1259
John McCallce3ff2b2009-08-25 22:02:44 +00001260/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001261/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001262QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001263TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001264 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1265 bool InvalidDecl = false;
1266
John McCallce3ff2b2009-08-25 22:02:44 +00001267 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001268 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001269 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001271 PEnd = D->param_end();
1272 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001273 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001274 if (PInst->getType()->isVoidType()) {
1275 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1276 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001277 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001278 PInst->getType(),
1279 diag::err_abstract_type_in_decl,
1280 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001281 PInst->setInvalidDecl();
1282
1283 Params.push_back(PInst);
1284 ParamTys.push_back(PInst->getType());
1285
1286 if (PInst->isInvalidDecl())
1287 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001288 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001289 InvalidDecl = true;
1290 }
1291
1292 // FIXME: Deallocate dead declarations.
1293 if (InvalidDecl)
1294 return QualType();
1295
John McCall183700f2009-09-21 23:43:11 +00001296 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001297 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001298 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001299 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1300 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001301 if (ResultType.isNull())
1302 return QualType();
1303
Jay Foadbeaaccd2009-05-21 09:52:38 +00001304 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001305 Proto->isVariadic(), Proto->getTypeQuals(),
1306 D->getLocation(), D->getDeclName());
1307}
1308
Mike Stump1eb44332009-09-09 15:08:12 +00001309/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001310/// declaration (New) from the corresponding fields of its template (Tmpl).
1311///
1312/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001313bool
1314TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001315 FunctionDecl *Tmpl) {
1316 if (Tmpl->isDeleted())
1317 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregorcca9e962009-07-01 22:01:06 +00001319 // If we are performing substituting explicitly-specified template arguments
1320 // or deduced template arguments into a function template and we reach this
1321 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001322 // to keeping the new function template specialization. We therefore
1323 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001324 // into a template instantiation for this specific function template
1325 // specialization, which is not a SFINAE context, so that we diagnose any
1326 // further errors in the declaration itself.
1327 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1328 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1329 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1330 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001331 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001332 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001334 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001335 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001336 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1337 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001338 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001339 }
1340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Douglas Gregore53060f2009-06-25 22:08:12 +00001342 return false;
1343}
1344
Douglas Gregor5545e162009-03-24 00:38:23 +00001345/// \brief Initializes common fields of an instantiated method
1346/// declaration (New) from the corresponding fields of its template
1347/// (Tmpl).
1348///
1349/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001350bool
1351TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001352 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001353 if (InitFunctionInstantiation(New, Tmpl))
1354 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Douglas Gregor5545e162009-03-24 00:38:23 +00001356 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1357 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00001358 if (Tmpl->isVirtualAsWritten()) {
1359 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00001360 Record->setAggregate(false);
1361 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00001362 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +00001363 Record->setPolymorphic(true);
1364 }
Douglas Gregor5545e162009-03-24 00:38:23 +00001365
1366 // FIXME: attributes
1367 // FIXME: New needs a pointer to Tmpl
1368 return false;
1369}
Douglas Gregora58861f2009-05-13 20:28:22 +00001370
1371/// \brief Instantiate the definition of the given function from its
1372/// template.
1373///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001374/// \param PointOfInstantiation the point at which the instantiation was
1375/// required. Note that this is not precisely a "point of instantiation"
1376/// for the function, but it's close.
1377///
Douglas Gregora58861f2009-05-13 20:28:22 +00001378/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001379/// function template specialization or member function of a class template
1380/// specialization.
1381///
1382/// \param Recursive if true, recursively instantiates any functions that
1383/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001384///
1385/// \param DefinitionRequired if true, then we are performing an explicit
1386/// instantiation where the body of the function is required. Complain if
1387/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001388void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001389 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001390 bool Recursive,
1391 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001392 if (Function->isInvalidDecl())
1393 return;
1394
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001395 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001397 // Never instantiate an explicit specialization.
1398 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1399 return;
1400
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001401 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001402 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001403 Stmt *Pattern = 0;
1404 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001405 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001406
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001407 if (!Pattern) {
1408 if (DefinitionRequired) {
1409 if (Function->getPrimaryTemplate())
1410 Diag(PointOfInstantiation,
1411 diag::err_explicit_instantiation_undefined_func_template)
1412 << Function->getPrimaryTemplate();
1413 else
1414 Diag(PointOfInstantiation,
1415 diag::err_explicit_instantiation_undefined_member)
1416 << 1 << Function->getDeclName() << Function->getDeclContext();
1417
1418 if (PatternDecl)
1419 Diag(PatternDecl->getLocation(),
1420 diag::note_explicit_instantiation_here);
1421 }
1422
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001423 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001424 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001425
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001426 // C++0x [temp.explicit]p9:
1427 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001428 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001429 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001431 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001432 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001433 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001435 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1436 if (Inst)
1437 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001438
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001439 // If we're performing recursive template instantiation, create our own
1440 // queue of pending implicit instantiations that we will instantiate later,
1441 // while we're still within our own instantiation context.
1442 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1443 if (Recursive)
1444 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001446 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1447
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001448 // Introduce a new scope where local variable instantiations will be
1449 // recorded.
1450 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001452 // Introduce the instantiated function parameters into the local
1453 // instantiation scope.
1454 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1455 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1456 Function->getParamDecl(I));
1457
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001458 // Enter the scope of this instantiation. We don't use
1459 // PushDeclContext because we don't have a scope.
1460 DeclContext *PreviousContext = CurContext;
1461 CurContext = Function;
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001464 getTemplateInstantiationArgs(Function);
1465
1466 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001467 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001468 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1469 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1470 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001471 }
1472
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001473 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001474 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001475
Douglas Gregor52604ab2009-09-11 21:19:12 +00001476 if (Body.isInvalid())
1477 Function->setInvalidDecl();
1478
Mike Stump1eb44332009-09-09 15:08:12 +00001479 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001480 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001481
1482 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001483
1484 DeclGroupRef DG(Function);
1485 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001487 if (Recursive) {
1488 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001489 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001490 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001492 // Restore the set of pending implicit instantiations.
1493 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1494 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001495}
1496
1497/// \brief Instantiate the definition of the given variable from its
1498/// template.
1499///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001500/// \param PointOfInstantiation the point at which the instantiation was
1501/// required. Note that this is not precisely a "point of instantiation"
1502/// for the function, but it's close.
1503///
1504/// \param Var the already-instantiated declaration of a static member
1505/// variable of a class template specialization.
1506///
1507/// \param Recursive if true, recursively instantiates any functions that
1508/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001509///
1510/// \param DefinitionRequired if true, then we are performing an explicit
1511/// instantiation where an out-of-line definition of the member variable
1512/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001513void Sema::InstantiateStaticDataMemberDefinition(
1514 SourceLocation PointOfInstantiation,
1515 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001516 bool Recursive,
1517 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001518 if (Var->isInvalidDecl())
1519 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Douglas Gregor7caa6822009-07-24 20:34:43 +00001521 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001522 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001523 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001524 assert(Def->isStaticDataMember() && "Not a static data member?");
1525 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Douglas Gregor0d035142009-10-27 18:42:08 +00001527 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001528 // We did not find an out-of-line definition of this static data member,
1529 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001530 // instantiate this definition (or provide a specialization for it) in
1531 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001532 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001533 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001534 Diag(PointOfInstantiation,
1535 diag::err_explicit_instantiation_undefined_member)
1536 << 2 << Var->getDeclName() << Var->getDeclContext();
1537 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1538 }
1539
Douglas Gregor7caa6822009-07-24 20:34:43 +00001540 return;
1541 }
1542
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001543 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001544 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001545 return;
1546
1547 // C++0x [temp.explicit]p9:
1548 // Except for inline functions, other explicit instantiation declarations
1549 // have the effect of suppressing the implicit instantiation of the entity
1550 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001551 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001552 == TSK_ExplicitInstantiationDeclaration)
1553 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Douglas Gregor7caa6822009-07-24 20:34:43 +00001555 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1556 if (Inst)
1557 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Douglas Gregor7caa6822009-07-24 20:34:43 +00001559 // If we're performing recursive template instantiation, create our own
1560 // queue of pending implicit instantiations that we will instantiate later,
1561 // while we're still within our own instantiation context.
1562 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1563 if (Recursive)
1564 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Douglas Gregor7caa6822009-07-24 20:34:43 +00001566 // Enter the scope of this instantiation. We don't use
1567 // PushDeclContext because we don't have a scope.
1568 DeclContext *PreviousContext = CurContext;
1569 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001571 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001572 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001573 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001574 CurContext = PreviousContext;
1575
1576 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001577 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001578 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1579 assert(MSInfo && "Missing member specialization information?");
1580 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1581 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001582 DeclGroupRef DG(Var);
1583 Consumer.HandleTopLevelDecl(DG);
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Douglas Gregor7caa6822009-07-24 20:34:43 +00001586 if (Recursive) {
1587 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001588 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001589 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor7caa6822009-07-24 20:34:43 +00001591 // Restore the set of pending implicit instantiations.
1592 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001593 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001594}
Douglas Gregor815215d2009-05-27 05:35:12 +00001595
Anders Carlsson09025312009-08-29 05:16:22 +00001596void
1597Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1598 const CXXConstructorDecl *Tmpl,
1599 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Anders Carlsson09025312009-08-29 05:16:22 +00001601 llvm::SmallVector<MemInitTy*, 4> NewInits;
1602
1603 // Instantiate all the initializers.
1604 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001605 InitsEnd = Tmpl->init_end();
1606 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001607 CXXBaseOrMemberInitializer *Init = *Inits;
1608
1609 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Anders Carlsson09025312009-08-29 05:16:22 +00001611 // Instantiate all the arguments.
1612 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1613 Args != ArgsEnd; ++Args) {
1614 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1615
1616 if (NewArg.isInvalid())
1617 New->setInvalidDecl();
1618 else
1619 NewArgs.push_back(NewArg.takeAs<Expr>());
1620 }
1621
1622 MemInitResult NewInit;
1623
1624 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001625 QualType BaseType(Init->getBaseClass(), 0);
1626 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1627 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001628
1629 NewInit = BuildBaseInitializer(BaseType,
Mike Stump1eb44332009-09-09 15:08:12 +00001630 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001631 NewArgs.size(),
1632 Init->getSourceLocation(),
1633 Init->getRParenLoc(),
1634 New->getParent());
1635 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001636 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001638 // Is this an anonymous union?
1639 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001640 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001641 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001642 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1643 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001644
1645 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001646 NewArgs.size(),
1647 Init->getSourceLocation(),
1648 Init->getRParenLoc());
1649 }
1650
1651 if (NewInit.isInvalid())
1652 New->setInvalidDecl();
1653 else {
1654 // FIXME: It would be nice if ASTOwningVector had a release function.
1655 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Anders Carlsson09025312009-08-29 05:16:22 +00001657 NewInits.push_back((MemInitTy *)NewInit.get());
1658 }
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Anders Carlsson09025312009-08-29 05:16:22 +00001661 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001662 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001663 /*FIXME: ColonLoc */
1664 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001665 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001666}
1667
John McCall52a575a2009-08-29 08:11:13 +00001668// TODO: this could be templated if the various decl types used the
1669// same method name.
1670static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1671 ClassTemplateDecl *Instance) {
1672 Pattern = Pattern->getCanonicalDecl();
1673
1674 do {
1675 Instance = Instance->getCanonicalDecl();
1676 if (Pattern == Instance) return true;
1677 Instance = Instance->getInstantiatedFromMemberTemplate();
1678 } while (Instance);
1679
1680 return false;
1681}
1682
Douglas Gregor0d696532009-09-28 06:34:35 +00001683static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1684 FunctionTemplateDecl *Instance) {
1685 Pattern = Pattern->getCanonicalDecl();
1686
1687 do {
1688 Instance = Instance->getCanonicalDecl();
1689 if (Pattern == Instance) return true;
1690 Instance = Instance->getInstantiatedFromMemberTemplate();
1691 } while (Instance);
1692
1693 return false;
1694}
1695
Douglas Gregored9c0f92009-10-29 00:04:11 +00001696static bool
1697isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1698 ClassTemplatePartialSpecializationDecl *Instance) {
1699 Pattern
1700 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1701 do {
1702 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1703 Instance->getCanonicalDecl());
1704 if (Pattern == Instance)
1705 return true;
1706 Instance = Instance->getInstantiatedFromMember();
1707 } while (Instance);
1708
1709 return false;
1710}
1711
John McCall52a575a2009-08-29 08:11:13 +00001712static bool isInstantiationOf(CXXRecordDecl *Pattern,
1713 CXXRecordDecl *Instance) {
1714 Pattern = Pattern->getCanonicalDecl();
1715
1716 do {
1717 Instance = Instance->getCanonicalDecl();
1718 if (Pattern == Instance) return true;
1719 Instance = Instance->getInstantiatedFromMemberClass();
1720 } while (Instance);
1721
1722 return false;
1723}
1724
1725static bool isInstantiationOf(FunctionDecl *Pattern,
1726 FunctionDecl *Instance) {
1727 Pattern = Pattern->getCanonicalDecl();
1728
1729 do {
1730 Instance = Instance->getCanonicalDecl();
1731 if (Pattern == Instance) return true;
1732 Instance = Instance->getInstantiatedFromMemberFunction();
1733 } while (Instance);
1734
1735 return false;
1736}
1737
1738static bool isInstantiationOf(EnumDecl *Pattern,
1739 EnumDecl *Instance) {
1740 Pattern = Pattern->getCanonicalDecl();
1741
1742 do {
1743 Instance = Instance->getCanonicalDecl();
1744 if (Pattern == Instance) return true;
1745 Instance = Instance->getInstantiatedFromMemberEnum();
1746 } while (Instance);
1747
1748 return false;
1749}
1750
John McCall7ba107a2009-11-18 02:36:19 +00001751static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1752 UsingDecl *Instance,
1753 ASTContext &C) {
1754 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1755}
1756
1757static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001758 UsingDecl *Instance,
1759 ASTContext &C) {
1760 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1761}
1762
John McCall52a575a2009-08-29 08:11:13 +00001763static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1764 VarDecl *Instance) {
1765 assert(Instance->isStaticDataMember());
1766
1767 Pattern = Pattern->getCanonicalDecl();
1768
1769 do {
1770 Instance = Instance->getCanonicalDecl();
1771 if (Pattern == Instance) return true;
1772 Instance = Instance->getInstantiatedFromStaticDataMember();
1773 } while (Instance);
1774
1775 return false;
1776}
1777
Douglas Gregor815215d2009-05-27 05:35:12 +00001778static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001779 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001780 if (UnresolvedUsingTypenameDecl *UUD
1781 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1782 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1783 return isInstantiationOf(UUD, UD, Ctx);
1784 }
1785 }
1786
1787 if (UnresolvedUsingValueDecl *UUD
1788 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001789 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1790 return isInstantiationOf(UUD, UD, Ctx);
1791 }
1792 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001793
Anders Carlsson0d8df782009-08-29 19:37:28 +00001794 return false;
1795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796
John McCall52a575a2009-08-29 08:11:13 +00001797 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1798 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
John McCall52a575a2009-08-29 08:11:13 +00001800 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1801 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001802
John McCall52a575a2009-08-29 08:11:13 +00001803 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1804 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001805
Douglas Gregor7caa6822009-07-24 20:34:43 +00001806 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001807 if (Var->isStaticDataMember())
1808 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1809
1810 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1811 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001812
Douglas Gregor0d696532009-09-28 06:34:35 +00001813 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1814 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1815
Douglas Gregored9c0f92009-10-29 00:04:11 +00001816 if (ClassTemplatePartialSpecializationDecl *PartialSpec
1817 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1818 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1819 PartialSpec);
1820
Anders Carlssond8b285f2009-09-01 04:26:58 +00001821 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1822 if (!Field->getDeclName()) {
1823 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001824 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001825 cast<FieldDecl>(D);
1826 }
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Douglas Gregor815215d2009-05-27 05:35:12 +00001829 return D->getDeclName() && isa<NamedDecl>(Other) &&
1830 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1831}
1832
1833template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001834static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001835 NamedDecl *D,
1836 ForwardIterator first,
1837 ForwardIterator last) {
1838 for (; first != last; ++first)
1839 if (isInstantiationOf(Ctx, D, *first))
1840 return cast<NamedDecl>(*first);
1841
1842 return 0;
1843}
1844
John McCall02cace72009-08-28 07:59:38 +00001845/// \brief Finds the instantiation of the given declaration context
1846/// within the current instantiation.
1847///
1848/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001849DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1850 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001851 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001852 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001853 return cast_or_null<DeclContext>(ID);
1854 } else return DC;
1855}
1856
Douglas Gregored961e72009-05-27 17:54:46 +00001857/// \brief Find the instantiation of the given declaration within the
1858/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001859///
1860/// This routine is intended to be used when \p D is a declaration
1861/// referenced from within a template, that needs to mapped into the
1862/// corresponding declaration within an instantiation. For example,
1863/// given:
1864///
1865/// \code
1866/// template<typename T>
1867/// struct X {
1868/// enum Kind {
1869/// KnownValue = sizeof(T)
1870/// };
1871///
1872/// bool getKind() const { return KnownValue; }
1873/// };
1874///
1875/// template struct X<int>;
1876/// \endcode
1877///
1878/// In the instantiation of X<int>::getKind(), we need to map the
1879/// EnumConstantDecl for KnownValue (which refers to
1880/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001881/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1882/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001883NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1884 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001885 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001886 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1887 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1888 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001889 // D is a local of some kind. Look into the map of local
1890 // declarations to their instantiations.
1891 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1892 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001893
Douglas Gregore95b4092009-09-16 18:34:49 +00001894 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1895 if (!Record->isDependentContext())
1896 return D;
1897
1898 // If the RecordDecl is actually the injected-class-name or a "templated"
1899 // declaration for a class template or class template partial
1900 // specialization, substitute into the injected-class-name of the
1901 // class template or partial specialization to find the new DeclContext.
1902 QualType T;
1903 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1904
1905 if (ClassTemplate) {
1906 T = ClassTemplate->getInjectedClassNameType(Context);
1907 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1908 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1909 T = Context.getTypeDeclType(Record);
1910 ClassTemplate = PartialSpec->getSpecializedTemplate();
1911 }
1912
1913 if (!T.isNull()) {
1914 // Substitute into the injected-class-name to get the type corresponding
1915 // to the instantiation we want. This substitution should never fail,
1916 // since we know we can instantiate the injected-class-name or we wouldn't
1917 // have gotten to the injected-class-name!
1918 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1919 // instantiation in the common case?
1920 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1921 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1922
1923 if (!T->isDependentType()) {
1924 assert(T->isRecordType() && "Instantiation must produce a record type");
1925 return T->getAs<RecordType>()->getDecl();
1926 }
1927
1928 // We are performing "partial" template instantiation to create the
1929 // member declarations for the members of a class template
1930 // specialization. Therefore, D is actually referring to something in
1931 // the current instantiation. Look through the current context,
1932 // which contains actual instantiations, to find the instantiation of
1933 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001934 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001935 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001936 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001937 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001938 if (isInstantiationOf(ClassTemplate,
1939 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001940 return Spec;
1941 }
1942
Mike Stump1eb44332009-09-09 15:08:12 +00001943 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001944 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001945 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001946 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001947
1948 // Fall through to deal with other dependent record types (e.g.,
1949 // anonymous unions in class templates).
1950 }
John McCall52a575a2009-08-29 08:11:13 +00001951
Douglas Gregore95b4092009-09-16 18:34:49 +00001952 if (!ParentDC->isDependentContext())
1953 return D;
1954
1955 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001956 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001957 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor815215d2009-05-27 05:35:12 +00001959 if (ParentDC != D->getDeclContext()) {
1960 // We performed some kind of instantiation in the parent context,
1961 // so now we need to look into the instantiated parent context to
1962 // find the instantiation of the declaration D.
1963 NamedDecl *Result = 0;
1964 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001965 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001966 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1967 } else {
1968 // Since we don't have a name for the entity we're looking for,
1969 // our only option is to walk through all of the declarations to
1970 // find that name. This will occur in a few cases:
1971 //
1972 // - anonymous struct/union within a template
1973 // - unnamed class/struct/union/enum within a template
1974 //
1975 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001976 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001977 ParentDC->decls_begin(),
1978 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor815215d2009-05-27 05:35:12 +00001981 assert(Result && "Unable to find instantiation of declaration!");
1982 D = Result;
1983 }
1984
Douglas Gregor815215d2009-05-27 05:35:12 +00001985 return D;
1986}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001987
Mike Stump1eb44332009-09-09 15:08:12 +00001988/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001989/// instantiations we have seen until this point.
1990void Sema::PerformPendingImplicitInstantiations() {
1991 while (!PendingImplicitInstantiations.empty()) {
1992 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001993 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Douglas Gregor7caa6822009-07-24 20:34:43 +00001995 // Instantiate function definitions
1996 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001997 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001998 Function->getLocation(), *this,
1999 Context.getSourceManager(),
2000 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002002 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002003 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002004 continue;
2005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Douglas Gregor7caa6822009-07-24 20:34:43 +00002007 // Instantiate static data member definitions.
2008 VarDecl *Var = cast<VarDecl>(Inst.first);
2009 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002010
Mike Stump1eb44332009-09-09 15:08:12 +00002011 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002012 Var->getLocation(), *this,
2013 Context.getSourceManager(),
2014 "instantiating static data member "
2015 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Douglas Gregor7caa6822009-07-24 20:34:43 +00002017 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002018 }
2019}