blob: bda19f1e988f81e1f974c7eeeef285faa5a9f28a [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#include "llvm/Support/Compiler.h"
22
23using namespace clang;
24
25namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000026 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000070 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
71 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor8dbc2692009-03-17 21:15:40 +000073 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000074 Decl *VisitDecl(Decl *D) {
75 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
76 Diagnostic::Error,
77 "cannot instantiate %0 yet");
78 SemaRef.Diag(D->getLocation(), DiagID)
79 << D->getDeclKindName();
80
Douglas Gregor8dbc2692009-03-17 21:15:40 +000081 return 0;
82 }
Douglas Gregor5545e162009-03-24 00:38:23 +000083
John McCallfd810b12009-08-14 02:03:10 +000084 const LangOptions &getLangOptions() {
85 return SemaRef.getLangOptions();
86 }
87
Douglas Gregor5545e162009-03-24 00:38:23 +000088 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000089 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000090 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000091 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000092 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000093
94 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000095 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000096
97 bool InstantiateClassTemplatePartialSpecialization(
98 ClassTemplateDecl *ClassTemplate,
99 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000100 };
101}
102
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000103// FIXME: Is this too simple?
104void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
105 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
106 TmplAttr = TmplAttr->getNext()) {
107
108 // FIXME: Is cloning correct for all attributes?
109 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
110
111 New->addAttr(NewAttr);
112 }
113}
114
Douglas Gregor4f722be2009-03-25 15:45:12 +0000115Decl *
116TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
117 assert(false && "Translation units cannot be instantiated");
118 return D;
119}
120
121Decl *
122TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
123 assert(false && "Namespaces cannot be instantiated");
124 return D;
125}
126
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000127Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
128 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000129 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
130 if (DI->getType()->isDependentType()) {
131 DI = SemaRef.SubstType(DI, TemplateArgs,
132 D->getLocation(), D->getDeclName());
133 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000134 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000135 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 }
137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 // Create the new typedef
140 TypedefDecl *Typedef
141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000142 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 if (Invalid)
144 Typedef->setInvalidDecl();
145
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000146 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000148 return Typedef;
149}
150
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000152 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000153 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
154 TemplateArgs,
155 D->getTypeSpecStartLoc(),
156 D->getDeclName());
157 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 return 0;
159
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000160 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000161 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
162 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000163 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000164 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000165 Var->setThreadSpecified(D->isThreadSpecified());
166 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
167 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000168
169 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000170 // out-of-line, the instantiation will have the same lexical
171 // context (which will be a namespace scope) as the template.
172 if (D->isOutOfLine())
173 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Mike Stump390b4cc2009-05-16 07:39:55 +0000175 // FIXME: In theory, we could have a previous declaration for variables that
176 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000177 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000178 // FIXME: having to fake up a LookupResult is dumb.
179 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
180 Sema::LookupOrdinaryName);
181 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Douglas Gregor7caa6822009-07-24 20:34:43 +0000183 if (D->isOutOfLine()) {
184 D->getLexicalDeclContext()->addDecl(Var);
185 Owner->makeDeclVisibleInContext(Var);
186 } else {
187 Owner->addDecl(Var);
188 }
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000190 // Link instantiations of static data members back to the template from
191 // which they were instantiated.
192 if (Var->isStaticDataMember())
193 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000194 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000195
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 if (D->getInit()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000197 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000198 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000199 if (Init.isInvalid())
200 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000201 else if (!D->getType()->isDependentType() &&
202 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000203 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000204 // If neither the declaration's type nor its initializer are dependent,
205 // we don't want to redo all the checking, especially since the
206 // initializer might have been wrapped by a CXXConstructExpr since we did
207 // it the first time.
Anders Carlssona244dc32009-11-24 16:52:50 +0000208 Var->setType(D->getType());
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000209 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
210 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000211 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000212 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000213 // Do we even need these comma locations?
214 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
215 if (PLE->getNumExprs() > 0) {
216 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
217 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
218 Expr *E = PLE->getExpr(I)->Retain();
219 FakeCommaLocs.push_back(
220 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
221 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000222 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Douglas Gregor83ddad32009-08-26 21:14:46 +0000225 // Add the direct initializer to the declaration.
226 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000227 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000228 Sema::MultiExprArg(SemaRef,
229 (void**)PLE->getExprs(),
230 PLE->getNumExprs()),
231 FakeCommaLocs.data(),
232 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Douglas Gregor83ddad32009-08-26 21:14:46 +0000234 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
235 // we've explicitly retained all of its subexpressions already.
236 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000237 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000238 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000239 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
240 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000241
242 return Var;
243}
244
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
246 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000247 DeclaratorInfo *DI = D->getDeclaratorInfo();
248 if (DI->getType()->isDependentType()) {
249 DI = SemaRef.SubstType(DI, TemplateArgs,
250 D->getLocation(), D->getDeclName());
251 if (!DI) {
252 DI = D->getDeclaratorInfo();
253 Invalid = true;
254 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000255 // C++ [temp.arg.type]p3:
256 // If a declaration acquires a function type through a type
257 // dependent on a template-parameter and this causes a
258 // declaration that does not use the syntactic form of a
259 // function declarator to have function type, the program is
260 // ill-formed.
261 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000262 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000263 Invalid = true;
264 }
265 }
266
267 Expr *BitWidth = D->getBitWidth();
268 if (Invalid)
269 BitWidth = 0;
270 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000271 // The bit-width expression is not potentially evaluated.
272 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000274 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000275 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000276 if (InstantiatedBitWidth.isInvalid()) {
277 Invalid = true;
278 BitWidth = 0;
279 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000280 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 }
282
John McCall07fb6be2009-10-22 23:33:21 +0000283 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
284 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000285 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000286 D->getLocation(),
287 D->isMutable(),
288 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000289 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000290 D->getAccess(),
291 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000292 if (!Field) {
293 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000294 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000295 }
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000297 InstantiateAttrs(D, Field);
298
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000299 if (Invalid)
300 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000302 if (!Field->getDeclName()) {
303 // Keep track of where this decl came from.
304 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000305 }
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000307 Field->setImplicit(D->isImplicit());
308 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000309
310 return Field;
311}
312
John McCall02cace72009-08-28 07:59:38 +0000313Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
314 FriendDecl::FriendUnion FU;
315
316 // Handle friend type expressions by simply substituting template
317 // parameters into the pattern type.
318 if (Type *Ty = D->getFriendType()) {
319 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
320 D->getLocation(), DeclarationName());
321 if (T.isNull()) return 0;
322
323 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
324 FU = T.getTypePtr();
325
326 // Handle everything else by appropriate substitution.
327 } else {
328 NamedDecl *ND = D->getFriendDecl();
329 assert(ND && "friend decl must be a decl or a type!");
330
Douglas Gregora735b202009-10-13 14:39:41 +0000331 // FIXME: We have a problem here, because the nested call to Visit(ND)
332 // will inject the thing that the friend references into the current
333 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000334 Decl *NewND = Visit(ND);
335 if (!NewND) return 0;
336
337 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000338 }
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCall02cace72009-08-28 07:59:38 +0000340 FriendDecl *FD =
341 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
342 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000343 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000344 Owner->addDecl(FD);
345 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000346}
347
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000348Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
349 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Douglas Gregorac7610d2009-06-22 20:57:11 +0000351 // The expression in a static assertion is not potentially evaluated.
352 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000354 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000355 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000356 if (InstantiatedAssertExpr.isInvalid())
357 return 0;
358
Douglas Gregor43d9d922009-08-08 01:41:12 +0000359 OwningExprResult Message(SemaRef, D->getMessage());
360 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000361 Decl *StaticAssert
362 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000363 move(InstantiatedAssertExpr),
364 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000365 return StaticAssert;
366}
367
368Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000369 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000371 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000372 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000373 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000374 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000375 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000376 Enum->startDefinition();
377
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000378 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000379
380 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000381 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
382 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383 EC != ECEnd; ++EC) {
384 // The specified value for the enumerator.
385 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000386 if (Expr *UninstValue = EC->getInitExpr()) {
387 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000388 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000389 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000390
John McCallce3ff2b2009-08-25 22:02:44 +0000391 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000392 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393
394 // Drop the initial value and continue.
395 bool isInvalid = false;
396 if (Value.isInvalid()) {
397 Value = SemaRef.Owned((Expr *)0);
398 isInvalid = true;
399 }
400
Mike Stump1eb44332009-09-09 15:08:12 +0000401 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000402 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
403 EC->getLocation(), EC->getIdentifier(),
404 move(Value));
405
406 if (isInvalid) {
407 if (EnumConst)
408 EnumConst->setInvalidDecl();
409 Enum->setInvalidDecl();
410 }
411
412 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000413 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000414 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000415 LastEnumConst = EnumConst;
416 }
417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000419 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000420 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000421 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
422 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000423 &Enumerators[0], Enumerators.size(),
424 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000425
426 return Enum;
427}
428
Douglas Gregor6477b692009-03-25 15:04:13 +0000429Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
430 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
431 return 0;
432}
433
Douglas Gregored9c0f92009-10-29 00:04:11 +0000434namespace {
435 class SortDeclByLocation {
436 SourceManager &SourceMgr;
437
438 public:
439 explicit SortDeclByLocation(SourceManager &SourceMgr)
440 : SourceMgr(SourceMgr) { }
441
442 bool operator()(const Decl *X, const Decl *Y) const {
443 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
444 Y->getLocation());
445 }
446 };
447}
448
John McCalle29ba202009-08-20 01:44:21 +0000449Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000450 // Create a local instantiation scope for this class template, which
451 // will contain the instantiations of the template parameters.
452 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000453 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000454 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000455 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000456 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000457
458 CXXRecordDecl *Pattern = D->getTemplatedDecl();
459 CXXRecordDecl *RecordInst
460 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
461 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000462 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
463 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000464
465 ClassTemplateDecl *Inst
466 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
467 D->getIdentifier(), InstParams, RecordInst, 0);
468 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000469 if (D->getFriendObjectKind())
470 Inst->setObjectOfFriendDecl(true);
471 else
472 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000473 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000474
475 // Trigger creation of the type for the instantiation.
476 SemaRef.Context.getTypeDeclType(RecordInst);
477
Douglas Gregor259571e2009-10-30 22:42:42 +0000478 // Finish handling of friends.
479 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000480 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000481 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000482
John McCalle29ba202009-08-20 01:44:21 +0000483 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000484
485 // First, we sort the partial specializations by location, so
486 // that we instantiate them in the order they were declared.
487 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
488 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
489 P = D->getPartialSpecializations().begin(),
490 PEnd = D->getPartialSpecializations().end();
491 P != PEnd; ++P)
492 PartialSpecs.push_back(&*P);
493 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
494 SortDeclByLocation(SemaRef.SourceMgr));
495
496 // Instantiate all of the partial specializations of this member class
497 // template.
498 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
499 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
500
John McCalle29ba202009-08-20 01:44:21 +0000501 return Inst;
502}
503
Douglas Gregord60e1052009-08-27 16:57:43 +0000504Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000505TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
506 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000507 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
508
509 // Lookup the already-instantiated declaration in the instantiation
510 // of the class template and return that.
511 DeclContext::lookup_result Found
512 = Owner->lookup(ClassTemplate->getDeclName());
513 if (Found.first == Found.second)
514 return 0;
515
516 ClassTemplateDecl *InstClassTemplate
517 = dyn_cast<ClassTemplateDecl>(*Found.first);
518 if (!InstClassTemplate)
519 return 0;
520
521 Decl *DCanon = D->getCanonicalDecl();
522 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
523 P = InstClassTemplate->getPartialSpecializations().begin(),
524 PEnd = InstClassTemplate->getPartialSpecializations().end();
525 P != PEnd; ++P) {
526 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
527 return &*P;
528 }
529
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000530 return 0;
531}
532
533Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000534TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000535 // Create a local instantiation scope for this function template, which
536 // will contain the instantiations of the template parameters and then get
537 // merged with the local instantiation scope for the function template
538 // itself.
539 Sema::LocalInstantiationScope Scope(SemaRef);
540
Douglas Gregord60e1052009-08-27 16:57:43 +0000541 TemplateParameterList *TempParams = D->getTemplateParameters();
542 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000543 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000544 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000545
Douglas Gregora735b202009-10-13 14:39:41 +0000546 FunctionDecl *Instantiated = 0;
547 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
548 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
549 InstParams));
550 else
551 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
552 D->getTemplatedDecl(),
553 InstParams));
554
555 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000556 return 0;
557
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000559 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000560 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000561 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000562 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000563 assert(InstTemplate &&
564 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
565 if (!InstTemplate->getInstantiatedFromMemberTemplate())
566 InstTemplate->setInstantiatedFromMemberTemplate(D);
567
568 // Add non-friends into the owner.
569 if (!InstTemplate->getFriendObjectKind())
570 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000571 return InstTemplate;
572}
573
Douglas Gregord475b8d2009-03-25 21:17:03 +0000574Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
575 CXXRecordDecl *PrevDecl = 0;
576 if (D->isInjectedClassName())
577 PrevDecl = cast<CXXRecordDecl>(Owner);
578
579 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000580 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000581 D->getLocation(), D->getIdentifier(),
582 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000583 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000584 // FIXME: Check against AS_none is an ugly hack to work around the issue that
585 // the tag decls introduced by friend class declarations don't have an access
586 // specifier. Remove once this area of the code gets sorted out.
587 if (D->getAccess() != AS_none)
588 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000589 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000590 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000591
John McCall02cace72009-08-28 07:59:38 +0000592 // If the original function was part of a friend declaration,
593 // inherit its namespace state.
594 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
595 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
596
Anders Carlssond8b285f2009-09-01 04:26:58 +0000597 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
598
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000599 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000600 return Record;
601}
602
John McCall02cace72009-08-28 07:59:38 +0000603/// Normal class members are of more specific types and therefore
604/// don't make it here. This function serves two purposes:
605/// 1) instantiating function templates
606/// 2) substituting friend declarations
607/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000608 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
609 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000610 // Check whether there is already a function template specialization for
611 // this declaration.
612 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
613 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000614 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000615 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000616 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000617 TemplateArgs.getInnermost().getFlatArgumentList(),
618 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000619 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000620
621 FunctionTemplateSpecializationInfo *Info
622 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000623 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Douglas Gregor127102b2009-06-29 20:59:39 +0000625 // If we already have a function template specialization, return it.
626 if (Info)
627 return Info->Function;
628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor550d9b22009-10-31 17:21:17 +0000630 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregore53060f2009-06-25 22:08:12 +0000632 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000633 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000634 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000635 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000636
Douglas Gregore53060f2009-06-25 22:08:12 +0000637 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000638 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
639 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000640 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000641 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000642 D->getDeclName(), T, D->getDeclaratorInfo(),
643 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000644 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000645 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Douglas Gregore53060f2009-06-25 22:08:12 +0000647 // Attach the parameters
648 for (unsigned P = 0; P < Params.size(); ++P)
649 Params[P]->setOwningFunction(Function);
650 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000651
Douglas Gregora735b202009-10-13 14:39:41 +0000652 if (TemplateParams) {
653 // Our resulting instantiation is actually a function template, since we
654 // are substituting only the outer template parameters. For example, given
655 //
656 // template<typename T>
657 // struct X {
658 // template<typename U> friend void f(T, U);
659 // };
660 //
661 // X<int> x;
662 //
663 // We are instantiating the friend function template "f" within X<int>,
664 // which means substituting int for T, but leaving "f" as a friend function
665 // template.
666 // Build the function template itself.
667 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
668 Function->getLocation(),
669 Function->getDeclName(),
670 TemplateParams, Function);
671 Function->setDescribedFunctionTemplate(FunctionTemplate);
672 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000673 } else if (FunctionTemplate) {
674 // Record this function template specialization.
675 Function->setFunctionTemplateSpecialization(SemaRef.Context,
676 FunctionTemplate,
677 &TemplateArgs.getInnermost(),
678 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000679 }
Douglas Gregora735b202009-10-13 14:39:41 +0000680
Douglas Gregore53060f2009-06-25 22:08:12 +0000681 if (InitFunctionInstantiation(Function, D))
682 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Douglas Gregore53060f2009-06-25 22:08:12 +0000684 bool Redeclaration = false;
685 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000686
John McCall68263142009-11-18 22:49:29 +0000687 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
688 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
689
Douglas Gregora735b202009-10-13 14:39:41 +0000690 if (TemplateParams || !FunctionTemplate) {
691 // Look only into the namespace where the friend would be declared to
692 // find a previous declaration. This is the innermost enclosing namespace,
693 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000694 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000695
Douglas Gregora735b202009-10-13 14:39:41 +0000696 // In C++, the previous declaration we find might be a tag type
697 // (class or enum). In this case, the new declaration will hide the
698 // tag type. Note that this does does not apply if we're declaring a
699 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000700 if (Previous.isSingleTagDecl())
701 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000702 }
703
John McCall68263142009-11-18 22:49:29 +0000704 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000705 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000706
Douglas Gregora735b202009-10-13 14:39:41 +0000707 // If the original function was part of a friend declaration,
708 // inherit its namespace state and add it to the owner.
709 NamedDecl *FromFriendD
710 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
711 if (FromFriendD->getFriendObjectKind()) {
712 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000713 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000714 if (TemplateParams) {
715 ToFriendD = cast<NamedDecl>(FunctionTemplate);
716 PrevDecl = FunctionTemplate->getPreviousDeclaration();
717 } else {
718 ToFriendD = Function;
719 PrevDecl = Function->getPreviousDeclaration();
720 }
721 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
722 if (!Owner->isDependentContext() && !PrevDecl)
723 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
724
725 if (!TemplateParams)
726 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
727 }
728
Douglas Gregore53060f2009-06-25 22:08:12 +0000729 return Function;
730}
731
Douglas Gregord60e1052009-08-27 16:57:43 +0000732Decl *
733TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
734 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000735 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
736 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000737 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000738 // We are creating a function template specialization from a function
739 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000740 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000741 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000742 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000743 TemplateArgs.getInnermost().getFlatArgumentList(),
744 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000745 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
747 FunctionTemplateSpecializationInfo *Info
748 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000749 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Douglas Gregor6b906862009-08-21 00:16:32 +0000751 // If we already have a function template specialization, return it.
752 if (Info)
753 return Info->Function;
754 }
755
Douglas Gregor550d9b22009-10-31 17:21:17 +0000756 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000757
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000758 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000759 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000760 if (T.isNull())
761 return 0;
762
763 // Build the instantiated method declaration.
764 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000765 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Douglas Gregordec06662009-08-21 18:42:58 +0000767 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000768 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000769 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
770 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
771 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000772 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
773 Constructor->getLocation(),
774 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000775 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000776 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000777 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000778 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
779 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
780 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
781 SemaRef.Context.getCanonicalType(ClassTy));
782 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
783 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000784 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000785 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000786 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000787 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000788 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000789 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
790 ConvTy);
791 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
792 Conversion->getLocation(), Name,
793 T, Conversion->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000794 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000795 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000796 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000797 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000798 D->getDeclName(), T, D->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000799 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000800 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000801
Douglas Gregord60e1052009-08-27 16:57:43 +0000802 if (TemplateParams) {
803 // Our resulting instantiation is actually a function template, since we
804 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000805 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000806 // template<typename T>
807 // struct X {
808 // template<typename U> void f(T, U);
809 // };
810 //
811 // X<int> x;
812 //
813 // We are instantiating the member template "f" within X<int>, which means
814 // substituting int for T, but leaving "f" as a member function template.
815 // Build the function template itself.
816 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
817 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000818 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000819 TemplateParams, Method);
820 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000821 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000822 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000823 } else if (FunctionTemplate) {
824 // Record this function template specialization.
825 Method->setFunctionTemplateSpecialization(SemaRef.Context,
826 FunctionTemplate,
827 &TemplateArgs.getInnermost(),
828 InsertPos);
829 } else {
830 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000831 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000832 }
833
Mike Stump1eb44332009-09-09 15:08:12 +0000834 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000835 // out-of-line, the instantiation will have the same lexical
836 // context (which will be a namespace scope) as the template.
837 if (D->isOutOfLine())
838 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor5545e162009-03-24 00:38:23 +0000840 // Attach the parameters
841 for (unsigned P = 0; P < Params.size(); ++P)
842 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000843 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000844
845 if (InitMethodInstantiation(Method, D))
846 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000847
John McCall68263142009-11-18 22:49:29 +0000848 LookupResult Previous(SemaRef, Name, SourceLocation(),
849 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregord60e1052009-08-27 16:57:43 +0000851 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000852 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregordec06662009-08-21 18:42:58 +0000854 // In C++, the previous declaration we find might be a tag type
855 // (class or enum). In this case, the new declaration will hide the
856 // tag type. Note that this does does not apply if we're declaring a
857 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000858 if (Previous.isSingleTagDecl())
859 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000860 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000861
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000862 bool Redeclaration = false;
863 bool OverloadableAttrRequired = false;
John McCall68263142009-11-18 22:49:29 +0000864 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000865 /*FIXME:*/OverloadableAttrRequired);
866
John McCall68263142009-11-18 22:49:29 +0000867 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000868 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000869 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Sebastian Redla165da02009-11-18 21:51:29 +0000871 SemaRef.AddOverriddenMethods(Record, Method);
872
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000873 return Method;
874}
875
Douglas Gregor615c5d42009-03-24 16:43:20 +0000876Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000877 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000878}
879
Douglas Gregor03b2b072009-03-24 00:15:49 +0000880Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000881 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000882}
883
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000884Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000885 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000886}
887
Douglas Gregor6477b692009-03-25 15:04:13 +0000888ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000889 QualType T;
890 DeclaratorInfo *DI = D->getDeclaratorInfo();
891 if (DI) {
892 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
893 D->getDeclName());
894 if (DI) T = DI->getType();
895 } else {
896 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
897 D->getDeclName());
898 DI = 0;
899 }
900
901 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000902 return 0;
903
John McCall58e46772009-10-23 21:48:59 +0000904 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000905
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000906 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000907 ParmVarDecl *Param
908 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
909 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000910
Anders Carlsson9351c172009-08-25 03:18:48 +0000911 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000912 if (D->hasUninstantiatedDefaultArg())
913 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000914 else if (Expr *Arg = D->getDefaultArg())
915 Param->setUninstantiatedDefaultArg(Arg);
916
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000917 // Note: we don't try to instantiate function parameters until after
918 // we've instantiated the function's type. Therefore, we don't have
919 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000920 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000921 return Param;
922}
923
John McCalle29ba202009-08-20 01:44:21 +0000924Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
925 TemplateTypeParmDecl *D) {
926 // TODO: don't always clone when decls are refcounted.
927 const Type* T = D->getTypeForDecl();
928 assert(T->isTemplateTypeParmType());
929 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
John McCalle29ba202009-08-20 01:44:21 +0000931 TemplateTypeParmDecl *Inst =
932 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000933 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000934 TTPT->getName(),
935 D->wasDeclaredWithTypename(),
936 D->isParameterPack());
937
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000938 if (D->hasDefaultArgument())
939 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000940
Douglas Gregor550d9b22009-10-31 17:21:17 +0000941 // Introduce this template parameter's instantiation into the instantiation
942 // scope.
943 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
944
John McCalle29ba202009-08-20 01:44:21 +0000945 return Inst;
946}
947
Douglas Gregor33642df2009-10-23 23:25:44 +0000948Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
949 NonTypeTemplateParmDecl *D) {
950 // Substitute into the type of the non-type template parameter.
951 QualType T;
952 DeclaratorInfo *DI = D->getDeclaratorInfo();
953 if (DI) {
954 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
955 D->getDeclName());
956 if (DI) T = DI->getType();
957 } else {
958 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
959 D->getDeclName());
960 DI = 0;
961 }
962 if (T.isNull())
963 return 0;
964
965 // Check that this type is acceptable for a non-type template parameter.
966 bool Invalid = false;
967 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
968 if (T.isNull()) {
969 T = SemaRef.Context.IntTy;
970 Invalid = true;
971 }
972
973 NonTypeTemplateParmDecl *Param
974 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
975 D->getDepth() - 1, D->getPosition(),
976 D->getIdentifier(), T, DI);
977 if (Invalid)
978 Param->setInvalidDecl();
979
980 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000981
982 // Introduce this template parameter's instantiation into the instantiation
983 // scope.
984 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000985 return Param;
986}
987
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000988Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000989TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
990 TemplateTemplateParmDecl *D) {
991 // Instantiate the template parameter list of the template template parameter.
992 TemplateParameterList *TempParams = D->getTemplateParameters();
993 TemplateParameterList *InstParams;
994 {
995 // Perform the actual substitution of template parameters within a new,
996 // local instantiation scope.
997 Sema::LocalInstantiationScope Scope(SemaRef);
998 InstParams = SubstTemplateParams(TempParams);
999 if (!InstParams)
1000 return NULL;
1001 }
1002
1003 // Build the template template parameter.
1004 TemplateTemplateParmDecl *Param
1005 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1006 D->getDepth() - 1, D->getPosition(),
1007 D->getIdentifier(), InstParams);
1008 Param->setDefaultArgument(D->getDefaultArgument());
1009
1010 // Introduce this template parameter's instantiation into the instantiation
1011 // scope.
1012 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1013
1014 return Param;
1015}
1016
Douglas Gregor48c32a72009-11-17 06:07:40 +00001017Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1018 // Using directives are never dependent, so they require no explicit
1019
1020 UsingDirectiveDecl *Inst
1021 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1022 D->getNamespaceKeyLocation(),
1023 D->getQualifierRange(), D->getQualifier(),
1024 D->getIdentLocation(),
1025 D->getNominatedNamespace(),
1026 D->getCommonAncestor());
1027 Owner->addDecl(Inst);
1028 return Inst;
1029}
1030
John McCall7ba107a2009-11-18 02:36:19 +00001031Decl * TemplateDeclInstantiator
1032 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001033 NestedNameSpecifier *NNS =
1034 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1035 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001036 TemplateArgs);
1037 if (!NNS)
1038 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001040 CXXScopeSpec SS;
1041 SS.setRange(D->getTargetNestedNameRange());
1042 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
1044 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001045 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001046 D->getUsingLoc(), SS, D->getLocation(),
1047 D->getDeclName(), 0,
1048 /*instantiation*/ true,
1049 /*typename*/ true, D->getTypenameLoc());
1050 if (UD)
1051 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1052 D);
1053 return UD;
1054}
1055
1056Decl * TemplateDeclInstantiator
1057 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1058 NestedNameSpecifier *NNS =
1059 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1060 D->getTargetNestedNameRange(),
1061 TemplateArgs);
1062 if (!NNS)
1063 return 0;
1064
1065 CXXScopeSpec SS;
1066 SS.setRange(D->getTargetNestedNameRange());
1067 SS.setScopeRep(NNS);
1068
1069 NamedDecl *UD =
1070 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1071 D->getUsingLoc(), SS, D->getLocation(),
1072 D->getDeclName(), 0,
1073 /*instantiation*/ true,
1074 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001075 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +00001076 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +00001077 D);
1078 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001079}
1080
John McCallce3ff2b2009-08-25 22:02:44 +00001081Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001082 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001083 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001084 return Instantiator.Visit(D);
1085}
1086
John McCalle29ba202009-08-20 01:44:21 +00001087/// \brief Instantiates a nested template parameter list in the current
1088/// instantiation context.
1089///
1090/// \param L The parameter list to instantiate
1091///
1092/// \returns NULL if there was an error
1093TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001094TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001095 // Get errors for all the parameters before bailing out.
1096 bool Invalid = false;
1097
1098 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001099 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001100 ParamVector Params;
1101 Params.reserve(N);
1102 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1103 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001104 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001105 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001106 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001107 }
1108
1109 // Clean up if we had an error.
1110 if (Invalid) {
1111 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1112 PI != PE; ++PI)
1113 if (*PI)
1114 (*PI)->Destroy(SemaRef.Context);
1115 return NULL;
1116 }
1117
1118 TemplateParameterList *InstL
1119 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1120 L->getLAngleLoc(), &Params.front(), N,
1121 L->getRAngleLoc());
1122 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001123}
John McCalle29ba202009-08-20 01:44:21 +00001124
Douglas Gregored9c0f92009-10-29 00:04:11 +00001125/// \brief Instantiate the declaration of a class template partial
1126/// specialization.
1127///
1128/// \param ClassTemplate the (instantiated) class template that is partially
1129// specialized by the instantiation of \p PartialSpec.
1130///
1131/// \param PartialSpec the (uninstantiated) class template partial
1132/// specialization that we are instantiating.
1133///
1134/// \returns true if there was an error, false otherwise.
1135bool
1136TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1137 ClassTemplateDecl *ClassTemplate,
1138 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001139 // Create a local instantiation scope for this class template partial
1140 // specialization, which will contain the instantiations of the template
1141 // parameters.
1142 Sema::LocalInstantiationScope Scope(SemaRef);
1143
Douglas Gregored9c0f92009-10-29 00:04:11 +00001144 // Substitute into the template parameters of the class template partial
1145 // specialization.
1146 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1147 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1148 if (!InstParams)
1149 return true;
1150
1151 // Substitute into the template arguments of the class template partial
1152 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001153 const TemplateArgumentLoc *PartialSpecTemplateArgs
1154 = PartialSpec->getTemplateArgsAsWritten();
1155 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1156
John McCalld5532b62009-11-23 01:53:49 +00001157 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001158 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001159 TemplateArgumentLoc Loc;
1160 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001161 return true;
John McCalld5532b62009-11-23 01:53:49 +00001162 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001163 }
1164
1165
1166 // Check that the template argument list is well-formed for this
1167 // class template.
1168 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1169 InstTemplateArgs.size());
1170 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1171 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001172 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001173 false,
1174 Converted))
1175 return true;
1176
1177 // Figure out where to insert this class template partial specialization
1178 // in the member template's set of class template partial specializations.
1179 llvm::FoldingSetNodeID ID;
1180 ClassTemplatePartialSpecializationDecl::Profile(ID,
1181 Converted.getFlatArguments(),
1182 Converted.flatSize(),
1183 SemaRef.Context);
1184 void *InsertPos = 0;
1185 ClassTemplateSpecializationDecl *PrevDecl
1186 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1187 InsertPos);
1188
1189 // Build the canonical type that describes the converted template
1190 // arguments of the class template partial specialization.
1191 QualType CanonType
1192 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1193 Converted.getFlatArguments(),
1194 Converted.flatSize());
1195
1196 // Build the fully-sugared type for this class template
1197 // specialization as the user wrote in the specialization
1198 // itself. This means that we'll pretty-print the type retrieved
1199 // from the specialization's declaration the way that the user
1200 // actually wrote the specialization, rather than formatting the
1201 // name based on the "canonical" representation used to store the
1202 // template arguments in the specialization.
1203 QualType WrittenTy
1204 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001205 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001206 CanonType);
1207
1208 if (PrevDecl) {
1209 // We've already seen a partial specialization with the same template
1210 // parameters and template arguments. This can happen, for example, when
1211 // substituting the outer template arguments ends up causing two
1212 // class template partial specializations of a member class template
1213 // to have identical forms, e.g.,
1214 //
1215 // template<typename T, typename U>
1216 // struct Outer {
1217 // template<typename X, typename Y> struct Inner;
1218 // template<typename Y> struct Inner<T, Y>;
1219 // template<typename Y> struct Inner<U, Y>;
1220 // };
1221 //
1222 // Outer<int, int> outer; // error: the partial specializations of Inner
1223 // // have the same signature.
1224 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1225 << WrittenTy;
1226 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1227 << SemaRef.Context.getTypeDeclType(PrevDecl);
1228 return true;
1229 }
1230
1231
1232 // Create the class template partial specialization declaration.
1233 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1234 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1235 PartialSpec->getLocation(),
1236 InstParams,
1237 ClassTemplate,
1238 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001239 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001240 0);
1241 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1242 InstPartialSpec->setTypeAsWritten(WrittenTy);
1243
1244 // Add this partial specialization to the set of class template partial
1245 // specializations.
1246 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1247 InsertPos);
1248 return false;
1249}
1250
John McCallce3ff2b2009-08-25 22:02:44 +00001251/// \brief Does substitution on the type of the given function, including
1252/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001253///
John McCallce3ff2b2009-08-25 22:02:44 +00001254/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001255///
1256/// \param Params the instantiated parameter declarations
1257
John McCallce3ff2b2009-08-25 22:02:44 +00001258/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001259/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001260QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001261TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001262 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1263 bool InvalidDecl = false;
1264
John McCallce3ff2b2009-08-25 22:02:44 +00001265 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001266 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001267 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001268 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001269 PEnd = D->param_end();
1270 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001271 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001272 if (PInst->getType()->isVoidType()) {
1273 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1274 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001275 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001276 PInst->getType(),
1277 diag::err_abstract_type_in_decl,
1278 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001279 PInst->setInvalidDecl();
1280
1281 Params.push_back(PInst);
1282 ParamTys.push_back(PInst->getType());
1283
1284 if (PInst->isInvalidDecl())
1285 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001286 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001287 InvalidDecl = true;
1288 }
1289
1290 // FIXME: Deallocate dead declarations.
1291 if (InvalidDecl)
1292 return QualType();
1293
John McCall183700f2009-09-21 23:43:11 +00001294 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001295 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001296 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001297 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1298 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001299 if (ResultType.isNull())
1300 return QualType();
1301
Jay Foadbeaaccd2009-05-21 09:52:38 +00001302 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001303 Proto->isVariadic(), Proto->getTypeQuals(),
1304 D->getLocation(), D->getDeclName());
1305}
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001308/// declaration (New) from the corresponding fields of its template (Tmpl).
1309///
1310/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001311bool
1312TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001313 FunctionDecl *Tmpl) {
1314 if (Tmpl->isDeleted())
1315 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Douglas Gregorcca9e962009-07-01 22:01:06 +00001317 // If we are performing substituting explicitly-specified template arguments
1318 // or deduced template arguments into a function template and we reach this
1319 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001320 // to keeping the new function template specialization. We therefore
1321 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001322 // into a template instantiation for this specific function template
1323 // specialization, which is not a SFINAE context, so that we diagnose any
1324 // further errors in the declaration itself.
1325 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1326 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1327 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1328 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001329 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001330 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001331 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001332 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001333 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001334 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1335 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001336 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001337 }
1338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Douglas Gregore53060f2009-06-25 22:08:12 +00001340 return false;
1341}
1342
Douglas Gregor5545e162009-03-24 00:38:23 +00001343/// \brief Initializes common fields of an instantiated method
1344/// declaration (New) from the corresponding fields of its template
1345/// (Tmpl).
1346///
1347/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001348bool
1349TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001350 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001351 if (InitFunctionInstantiation(New, Tmpl))
1352 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Douglas Gregor5545e162009-03-24 00:38:23 +00001354 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1355 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00001356 if (Tmpl->isVirtualAsWritten()) {
1357 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00001358 Record->setAggregate(false);
1359 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00001360 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +00001361 Record->setPolymorphic(true);
1362 }
Douglas Gregor5545e162009-03-24 00:38:23 +00001363 if (Tmpl->isPure()) {
1364 New->setPure();
1365 Record->setAbstract(true);
1366 }
1367
1368 // FIXME: attributes
1369 // FIXME: New needs a pointer to Tmpl
1370 return false;
1371}
Douglas Gregora58861f2009-05-13 20:28:22 +00001372
1373/// \brief Instantiate the definition of the given function from its
1374/// template.
1375///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001376/// \param PointOfInstantiation the point at which the instantiation was
1377/// required. Note that this is not precisely a "point of instantiation"
1378/// for the function, but it's close.
1379///
Douglas Gregora58861f2009-05-13 20:28:22 +00001380/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001381/// function template specialization or member function of a class template
1382/// specialization.
1383///
1384/// \param Recursive if true, recursively instantiates any functions that
1385/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001386///
1387/// \param DefinitionRequired if true, then we are performing an explicit
1388/// instantiation where the body of the function is required. Complain if
1389/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001390void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001391 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001392 bool Recursive,
1393 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001394 if (Function->isInvalidDecl())
1395 return;
1396
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001397 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001399 // Never instantiate an explicit specialization.
1400 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1401 return;
1402
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001403 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001404 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001405 Stmt *Pattern = 0;
1406 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001407 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001408
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001409 if (!Pattern) {
1410 if (DefinitionRequired) {
1411 if (Function->getPrimaryTemplate())
1412 Diag(PointOfInstantiation,
1413 diag::err_explicit_instantiation_undefined_func_template)
1414 << Function->getPrimaryTemplate();
1415 else
1416 Diag(PointOfInstantiation,
1417 diag::err_explicit_instantiation_undefined_member)
1418 << 1 << Function->getDeclName() << Function->getDeclContext();
1419
1420 if (PatternDecl)
1421 Diag(PatternDecl->getLocation(),
1422 diag::note_explicit_instantiation_here);
1423 }
1424
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001425 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001426 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001427
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001428 // C++0x [temp.explicit]p9:
1429 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001431 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001432 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001433 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001434 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001435 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001437 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1438 if (Inst)
1439 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001440
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001441 // If we're performing recursive template instantiation, create our own
1442 // queue of pending implicit instantiations that we will instantiate later,
1443 // while we're still within our own instantiation context.
1444 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1445 if (Recursive)
1446 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001448 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1449
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001450 // Introduce a new scope where local variable instantiations will be
1451 // recorded.
1452 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001454 // Introduce the instantiated function parameters into the local
1455 // instantiation scope.
1456 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1457 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1458 Function->getParamDecl(I));
1459
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001460 // Enter the scope of this instantiation. We don't use
1461 // PushDeclContext because we don't have a scope.
1462 DeclContext *PreviousContext = CurContext;
1463 CurContext = Function;
1464
Mike Stump1eb44332009-09-09 15:08:12 +00001465 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001466 getTemplateInstantiationArgs(Function);
1467
1468 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001469 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001470 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1471 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1472 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001473 }
1474
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001475 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001476 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001477
Douglas Gregor52604ab2009-09-11 21:19:12 +00001478 if (Body.isInvalid())
1479 Function->setInvalidDecl();
1480
Mike Stump1eb44332009-09-09 15:08:12 +00001481 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001482 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001483
1484 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001485
1486 DeclGroupRef DG(Function);
1487 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001489 if (Recursive) {
1490 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001491 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001492 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001494 // Restore the set of pending implicit instantiations.
1495 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1496 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001497}
1498
1499/// \brief Instantiate the definition of the given variable from its
1500/// template.
1501///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001502/// \param PointOfInstantiation the point at which the instantiation was
1503/// required. Note that this is not precisely a "point of instantiation"
1504/// for the function, but it's close.
1505///
1506/// \param Var the already-instantiated declaration of a static member
1507/// variable of a class template specialization.
1508///
1509/// \param Recursive if true, recursively instantiates any functions that
1510/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001511///
1512/// \param DefinitionRequired if true, then we are performing an explicit
1513/// instantiation where an out-of-line definition of the member variable
1514/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001515void Sema::InstantiateStaticDataMemberDefinition(
1516 SourceLocation PointOfInstantiation,
1517 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001518 bool Recursive,
1519 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001520 if (Var->isInvalidDecl())
1521 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Douglas Gregor7caa6822009-07-24 20:34:43 +00001523 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001524 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001525 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001526 assert(Def->isStaticDataMember() && "Not a static data member?");
1527 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregor0d035142009-10-27 18:42:08 +00001529 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001530 // We did not find an out-of-line definition of this static data member,
1531 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001532 // instantiate this definition (or provide a specialization for it) in
1533 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001534 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001535 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001536 Diag(PointOfInstantiation,
1537 diag::err_explicit_instantiation_undefined_member)
1538 << 2 << Var->getDeclName() << Var->getDeclContext();
1539 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1540 }
1541
Douglas Gregor7caa6822009-07-24 20:34:43 +00001542 return;
1543 }
1544
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001545 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001546 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001547 return;
1548
1549 // C++0x [temp.explicit]p9:
1550 // Except for inline functions, other explicit instantiation declarations
1551 // have the effect of suppressing the implicit instantiation of the entity
1552 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001553 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001554 == TSK_ExplicitInstantiationDeclaration)
1555 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Douglas Gregor7caa6822009-07-24 20:34:43 +00001557 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1558 if (Inst)
1559 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Douglas Gregor7caa6822009-07-24 20:34:43 +00001561 // If we're performing recursive template instantiation, create our own
1562 // queue of pending implicit instantiations that we will instantiate later,
1563 // while we're still within our own instantiation context.
1564 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1565 if (Recursive)
1566 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregor7caa6822009-07-24 20:34:43 +00001568 // Enter the scope of this instantiation. We don't use
1569 // PushDeclContext because we don't have a scope.
1570 DeclContext *PreviousContext = CurContext;
1571 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001573 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001574 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001575 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001576 CurContext = PreviousContext;
1577
1578 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001579 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001580 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1581 assert(MSInfo && "Missing member specialization information?");
1582 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1583 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001584 DeclGroupRef DG(Var);
1585 Consumer.HandleTopLevelDecl(DG);
1586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Douglas Gregor7caa6822009-07-24 20:34:43 +00001588 if (Recursive) {
1589 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001590 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001591 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor7caa6822009-07-24 20:34:43 +00001593 // Restore the set of pending implicit instantiations.
1594 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001595 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001596}
Douglas Gregor815215d2009-05-27 05:35:12 +00001597
Anders Carlsson09025312009-08-29 05:16:22 +00001598void
1599Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1600 const CXXConstructorDecl *Tmpl,
1601 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Anders Carlsson09025312009-08-29 05:16:22 +00001603 llvm::SmallVector<MemInitTy*, 4> NewInits;
1604
1605 // Instantiate all the initializers.
1606 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001607 InitsEnd = Tmpl->init_end();
1608 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001609 CXXBaseOrMemberInitializer *Init = *Inits;
1610
1611 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Anders Carlsson09025312009-08-29 05:16:22 +00001613 // Instantiate all the arguments.
1614 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1615 Args != ArgsEnd; ++Args) {
1616 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1617
1618 if (NewArg.isInvalid())
1619 New->setInvalidDecl();
1620 else
1621 NewArgs.push_back(NewArg.takeAs<Expr>());
1622 }
1623
1624 MemInitResult NewInit;
1625
1626 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001627 QualType BaseType(Init->getBaseClass(), 0);
1628 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1629 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001630
1631 NewInit = BuildBaseInitializer(BaseType,
Mike Stump1eb44332009-09-09 15:08:12 +00001632 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001633 NewArgs.size(),
1634 Init->getSourceLocation(),
1635 Init->getRParenLoc(),
1636 New->getParent());
1637 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001638 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001640 // Is this an anonymous union?
1641 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001642 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001643 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001644 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1645 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001646
1647 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001648 NewArgs.size(),
1649 Init->getSourceLocation(),
1650 Init->getRParenLoc());
1651 }
1652
1653 if (NewInit.isInvalid())
1654 New->setInvalidDecl();
1655 else {
1656 // FIXME: It would be nice if ASTOwningVector had a release function.
1657 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlsson09025312009-08-29 05:16:22 +00001659 NewInits.push_back((MemInitTy *)NewInit.get());
1660 }
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Anders Carlsson09025312009-08-29 05:16:22 +00001663 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001664 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001665 /*FIXME: ColonLoc */
1666 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001667 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001668}
1669
John McCall52a575a2009-08-29 08:11:13 +00001670// TODO: this could be templated if the various decl types used the
1671// same method name.
1672static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1673 ClassTemplateDecl *Instance) {
1674 Pattern = Pattern->getCanonicalDecl();
1675
1676 do {
1677 Instance = Instance->getCanonicalDecl();
1678 if (Pattern == Instance) return true;
1679 Instance = Instance->getInstantiatedFromMemberTemplate();
1680 } while (Instance);
1681
1682 return false;
1683}
1684
Douglas Gregor0d696532009-09-28 06:34:35 +00001685static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1686 FunctionTemplateDecl *Instance) {
1687 Pattern = Pattern->getCanonicalDecl();
1688
1689 do {
1690 Instance = Instance->getCanonicalDecl();
1691 if (Pattern == Instance) return true;
1692 Instance = Instance->getInstantiatedFromMemberTemplate();
1693 } while (Instance);
1694
1695 return false;
1696}
1697
Douglas Gregored9c0f92009-10-29 00:04:11 +00001698static bool
1699isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1700 ClassTemplatePartialSpecializationDecl *Instance) {
1701 Pattern
1702 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1703 do {
1704 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1705 Instance->getCanonicalDecl());
1706 if (Pattern == Instance)
1707 return true;
1708 Instance = Instance->getInstantiatedFromMember();
1709 } while (Instance);
1710
1711 return false;
1712}
1713
John McCall52a575a2009-08-29 08:11:13 +00001714static bool isInstantiationOf(CXXRecordDecl *Pattern,
1715 CXXRecordDecl *Instance) {
1716 Pattern = Pattern->getCanonicalDecl();
1717
1718 do {
1719 Instance = Instance->getCanonicalDecl();
1720 if (Pattern == Instance) return true;
1721 Instance = Instance->getInstantiatedFromMemberClass();
1722 } while (Instance);
1723
1724 return false;
1725}
1726
1727static bool isInstantiationOf(FunctionDecl *Pattern,
1728 FunctionDecl *Instance) {
1729 Pattern = Pattern->getCanonicalDecl();
1730
1731 do {
1732 Instance = Instance->getCanonicalDecl();
1733 if (Pattern == Instance) return true;
1734 Instance = Instance->getInstantiatedFromMemberFunction();
1735 } while (Instance);
1736
1737 return false;
1738}
1739
1740static bool isInstantiationOf(EnumDecl *Pattern,
1741 EnumDecl *Instance) {
1742 Pattern = Pattern->getCanonicalDecl();
1743
1744 do {
1745 Instance = Instance->getCanonicalDecl();
1746 if (Pattern == Instance) return true;
1747 Instance = Instance->getInstantiatedFromMemberEnum();
1748 } while (Instance);
1749
1750 return false;
1751}
1752
John McCall7ba107a2009-11-18 02:36:19 +00001753static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1754 UsingDecl *Instance,
1755 ASTContext &C) {
1756 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1757}
1758
1759static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001760 UsingDecl *Instance,
1761 ASTContext &C) {
1762 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1763}
1764
John McCall52a575a2009-08-29 08:11:13 +00001765static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1766 VarDecl *Instance) {
1767 assert(Instance->isStaticDataMember());
1768
1769 Pattern = Pattern->getCanonicalDecl();
1770
1771 do {
1772 Instance = Instance->getCanonicalDecl();
1773 if (Pattern == Instance) return true;
1774 Instance = Instance->getInstantiatedFromStaticDataMember();
1775 } while (Instance);
1776
1777 return false;
1778}
1779
Douglas Gregor815215d2009-05-27 05:35:12 +00001780static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001781 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001782 if (UnresolvedUsingTypenameDecl *UUD
1783 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1784 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1785 return isInstantiationOf(UUD, UD, Ctx);
1786 }
1787 }
1788
1789 if (UnresolvedUsingValueDecl *UUD
1790 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001791 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1792 return isInstantiationOf(UUD, UD, Ctx);
1793 }
1794 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001795
Anders Carlsson0d8df782009-08-29 19:37:28 +00001796 return false;
1797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
John McCall52a575a2009-08-29 08:11:13 +00001799 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1800 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
John McCall52a575a2009-08-29 08:11:13 +00001802 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1803 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001804
John McCall52a575a2009-08-29 08:11:13 +00001805 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1806 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001807
Douglas Gregor7caa6822009-07-24 20:34:43 +00001808 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001809 if (Var->isStaticDataMember())
1810 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1811
1812 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1813 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001814
Douglas Gregor0d696532009-09-28 06:34:35 +00001815 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1816 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1817
Douglas Gregored9c0f92009-10-29 00:04:11 +00001818 if (ClassTemplatePartialSpecializationDecl *PartialSpec
1819 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1820 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1821 PartialSpec);
1822
Anders Carlssond8b285f2009-09-01 04:26:58 +00001823 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1824 if (!Field->getDeclName()) {
1825 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001826 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001827 cast<FieldDecl>(D);
1828 }
1829 }
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Douglas Gregor815215d2009-05-27 05:35:12 +00001831 return D->getDeclName() && isa<NamedDecl>(Other) &&
1832 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1833}
1834
1835template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001836static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001837 NamedDecl *D,
1838 ForwardIterator first,
1839 ForwardIterator last) {
1840 for (; first != last; ++first)
1841 if (isInstantiationOf(Ctx, D, *first))
1842 return cast<NamedDecl>(*first);
1843
1844 return 0;
1845}
1846
John McCall02cace72009-08-28 07:59:38 +00001847/// \brief Finds the instantiation of the given declaration context
1848/// within the current instantiation.
1849///
1850/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001851DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1852 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001853 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001854 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001855 return cast_or_null<DeclContext>(ID);
1856 } else return DC;
1857}
1858
Douglas Gregored961e72009-05-27 17:54:46 +00001859/// \brief Find the instantiation of the given declaration within the
1860/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001861///
1862/// This routine is intended to be used when \p D is a declaration
1863/// referenced from within a template, that needs to mapped into the
1864/// corresponding declaration within an instantiation. For example,
1865/// given:
1866///
1867/// \code
1868/// template<typename T>
1869/// struct X {
1870/// enum Kind {
1871/// KnownValue = sizeof(T)
1872/// };
1873///
1874/// bool getKind() const { return KnownValue; }
1875/// };
1876///
1877/// template struct X<int>;
1878/// \endcode
1879///
1880/// In the instantiation of X<int>::getKind(), we need to map the
1881/// EnumConstantDecl for KnownValue (which refers to
1882/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001883/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1884/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001885NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1886 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor44c73842009-09-01 17:53:10 +00001887 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1888 // Transform all of the elements of the overloaded function set.
Mike Stump1eb44332009-09-09 15:08:12 +00001889 OverloadedFunctionDecl *Result
Douglas Gregor44c73842009-09-01 17:53:10 +00001890 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Douglas Gregor44c73842009-09-01 17:53:10 +00001892 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1893 FEnd = Ovl->function_end();
1894 F != FEnd; ++F) {
1895 Result->addOverload(
Douglas Gregore95b4092009-09-16 18:34:49 +00001896 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1897 TemplateArgs)));
Douglas Gregor44c73842009-09-01 17:53:10 +00001898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor44c73842009-09-01 17:53:10 +00001900 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001901 }
1902
Douglas Gregor815215d2009-05-27 05:35:12 +00001903 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001904 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1905 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1906 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001907 // D is a local of some kind. Look into the map of local
1908 // declarations to their instantiations.
1909 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1910 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001911
Douglas Gregore95b4092009-09-16 18:34:49 +00001912 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1913 if (!Record->isDependentContext())
1914 return D;
1915
1916 // If the RecordDecl is actually the injected-class-name or a "templated"
1917 // declaration for a class template or class template partial
1918 // specialization, substitute into the injected-class-name of the
1919 // class template or partial specialization to find the new DeclContext.
1920 QualType T;
1921 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1922
1923 if (ClassTemplate) {
1924 T = ClassTemplate->getInjectedClassNameType(Context);
1925 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1926 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1927 T = Context.getTypeDeclType(Record);
1928 ClassTemplate = PartialSpec->getSpecializedTemplate();
1929 }
1930
1931 if (!T.isNull()) {
1932 // Substitute into the injected-class-name to get the type corresponding
1933 // to the instantiation we want. This substitution should never fail,
1934 // since we know we can instantiate the injected-class-name or we wouldn't
1935 // have gotten to the injected-class-name!
1936 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1937 // instantiation in the common case?
1938 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1939 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1940
1941 if (!T->isDependentType()) {
1942 assert(T->isRecordType() && "Instantiation must produce a record type");
1943 return T->getAs<RecordType>()->getDecl();
1944 }
1945
1946 // We are performing "partial" template instantiation to create the
1947 // member declarations for the members of a class template
1948 // specialization. Therefore, D is actually referring to something in
1949 // the current instantiation. Look through the current context,
1950 // which contains actual instantiations, to find the instantiation of
1951 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001952 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001953 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001954 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001955 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001956 if (isInstantiationOf(ClassTemplate,
1957 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001958 return Spec;
1959 }
1960
Mike Stump1eb44332009-09-09 15:08:12 +00001961 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001962 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001963 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001964 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001965
1966 // Fall through to deal with other dependent record types (e.g.,
1967 // anonymous unions in class templates).
1968 }
John McCall52a575a2009-08-29 08:11:13 +00001969
Douglas Gregore95b4092009-09-16 18:34:49 +00001970 if (!ParentDC->isDependentContext())
1971 return D;
1972
1973 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001974 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001975 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor815215d2009-05-27 05:35:12 +00001977 if (ParentDC != D->getDeclContext()) {
1978 // We performed some kind of instantiation in the parent context,
1979 // so now we need to look into the instantiated parent context to
1980 // find the instantiation of the declaration D.
1981 NamedDecl *Result = 0;
1982 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001983 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001984 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1985 } else {
1986 // Since we don't have a name for the entity we're looking for,
1987 // our only option is to walk through all of the declarations to
1988 // find that name. This will occur in a few cases:
1989 //
1990 // - anonymous struct/union within a template
1991 // - unnamed class/struct/union/enum within a template
1992 //
1993 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001994 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001995 ParentDC->decls_begin(),
1996 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001997 }
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Douglas Gregor815215d2009-05-27 05:35:12 +00001999 assert(Result && "Unable to find instantiation of declaration!");
2000 D = Result;
2001 }
2002
Douglas Gregor815215d2009-05-27 05:35:12 +00002003 return D;
2004}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002005
Mike Stump1eb44332009-09-09 15:08:12 +00002006/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002007/// instantiations we have seen until this point.
2008void Sema::PerformPendingImplicitInstantiations() {
2009 while (!PendingImplicitInstantiations.empty()) {
2010 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002011 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Douglas Gregor7caa6822009-07-24 20:34:43 +00002013 // Instantiate function definitions
2014 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002015 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002016 Function->getLocation(), *this,
2017 Context.getSourceManager(),
2018 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002020 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002021 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002022 continue;
2023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Douglas Gregor7caa6822009-07-24 20:34:43 +00002025 // Instantiate static data member definitions.
2026 VarDecl *Var = cast<VarDecl>(Inst.first);
2027 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002028
Mike Stump1eb44332009-09-09 15:08:12 +00002029 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002030 Var->getLocation(), *this,
2031 Context.getSourceManager(),
2032 "instantiating static data member "
2033 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Douglas Gregor7caa6822009-07-24 20:34:43 +00002035 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002036 }
2037}