blob: e8bcb8be89b0142d7459fb565bace5b0f944bffe [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"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000021#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000022#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000023
24using namespace clang;
25
26namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000027 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000028 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029 Sema &SemaRef;
30 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000031 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Anders Carlssond8fe2d52009-11-07 06:07:58 +000033 void InstantiateAttrs(Decl *Tmpl, Decl *New);
34
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035 public:
36 typedef Sema::OwningExprResult OwningExprResult;
37
38 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000039 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000040 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000041
Mike Stump390b4cc2009-05-16 07:39:55 +000042 // FIXME: Once we get closer to completion, replace these manually-written
43 // declarations with automatically-generated ones from
44 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000045 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
46 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000047 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000049 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000050 Decl *VisitFieldDecl(FieldDecl *D);
51 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
52 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000054 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000055 Decl *VisitFunctionDecl(FunctionDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000057 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000058 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
59 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000060 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000061 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000062 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000063 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000064 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000065 Decl *VisitClassTemplatePartialSpecializationDecl(
66 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000067 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000068 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000069 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000070 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000071 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000072 Decl *VisitUsingDecl(UsingDecl *D);
73 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000074 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
75 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Douglas Gregor8dbc2692009-03-17 21:15:40 +000077 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000078 Decl *VisitDecl(Decl *D) {
79 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
80 Diagnostic::Error,
81 "cannot instantiate %0 yet");
82 SemaRef.Diag(D->getLocation(), DiagID)
83 << D->getDeclKindName();
84
Douglas Gregor8dbc2692009-03-17 21:15:40 +000085 return 0;
86 }
Douglas Gregor5545e162009-03-24 00:38:23 +000087
John McCallfd810b12009-08-14 02:03:10 +000088 const LangOptions &getLangOptions() {
89 return SemaRef.getLangOptions();
90 }
91
Douglas Gregor5545e162009-03-24 00:38:23 +000092 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000093 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000094 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000095 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000096 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000097
98 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000099 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000100
101 bool InstantiateClassTemplatePartialSpecialization(
102 ClassTemplateDecl *ClassTemplate,
103 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000104 };
105}
106
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000107// FIXME: Is this too simple?
108void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
109 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
110 TmplAttr = TmplAttr->getNext()) {
111
112 // FIXME: Is cloning correct for all attributes?
113 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
114
115 New->addAttr(NewAttr);
116 }
117}
118
Douglas Gregor4f722be2009-03-25 15:45:12 +0000119Decl *
120TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
121 assert(false && "Translation units cannot be instantiated");
122 return D;
123}
124
125Decl *
126TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
127 assert(false && "Namespaces cannot be instantiated");
128 return D;
129}
130
John McCall3dbd3d52010-02-16 06:53:13 +0000131Decl *
132TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
133 NamespaceAliasDecl *Inst
134 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
135 D->getNamespaceLoc(),
136 D->getAliasLoc(),
137 D->getNamespace()->getIdentifier(),
138 D->getQualifierRange(),
139 D->getQualifier(),
140 D->getTargetNameLoc(),
141 D->getNamespace());
142 Owner->addDecl(Inst);
143 return Inst;
144}
145
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000146Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
147 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000148 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000149 if (DI->getType()->isDependentType()) {
150 DI = SemaRef.SubstType(DI, TemplateArgs,
151 D->getLocation(), D->getDeclName());
152 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000153 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000154 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000155 }
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000158 // Create the new typedef
159 TypedefDecl *Typedef
160 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000161 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000162 if (Invalid)
163 Typedef->setInvalidDecl();
164
John McCall5126fd02009-12-30 00:31:22 +0000165 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000166 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
167 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000168 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
169 }
170
John McCall46460a62010-01-20 21:53:11 +0000171 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000172 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000174 return Typedef;
175}
176
Douglas Gregor6eef5192009-12-14 19:27:10 +0000177/// \brief Instantiate the arguments provided as part of initialization.
178///
179/// \returns true if an error occurred, false otherwise.
180static bool InstantiateInitializationArguments(Sema &SemaRef,
181 Expr **Args, unsigned NumArgs,
182 const MultiLevelTemplateArgumentList &TemplateArgs,
183 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
184 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
185 for (unsigned I = 0; I != NumArgs; ++I) {
186 // When we hit the first defaulted argument, break out of the loop:
187 // we don't pass those default arguments on.
188 if (Args[I]->isDefaultArgument())
189 break;
190
191 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
192 if (Arg.isInvalid())
193 return true;
194
195 Expr *ArgExpr = (Expr *)Arg.get();
196 InitArgs.push_back(Arg.release());
197
198 // FIXME: We're faking all of the comma locations. Do we need them?
199 FakeCommaLocs.push_back(
200 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
201 }
202
203 return false;
204}
205
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000206/// \brief Instantiate an initializer, breaking it into separate
207/// initialization arguments.
208///
209/// \param S The semantic analysis object.
210///
211/// \param Init The initializer to instantiate.
212///
213/// \param TemplateArgs Template arguments to be substituted into the
214/// initializer.
215///
216/// \param NewArgs Will be filled in with the instantiation arguments.
217///
218/// \returns true if an error occurred, false otherwise
219static bool InstantiateInitializer(Sema &S, Expr *Init,
220 const MultiLevelTemplateArgumentList &TemplateArgs,
221 SourceLocation &LParenLoc,
222 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
223 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
224 SourceLocation &RParenLoc) {
225 NewArgs.clear();
226 LParenLoc = SourceLocation();
227 RParenLoc = SourceLocation();
228
229 if (!Init)
230 return false;
231
232 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
233 Init = ExprTemp->getSubExpr();
234
235 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
236 Init = Binder->getSubExpr();
237
238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
239 Init = ICE->getSubExprAsWritten();
240
241 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
242 LParenLoc = ParenList->getLParenLoc();
243 RParenLoc = ParenList->getRParenLoc();
244 return InstantiateInitializationArguments(S, ParenList->getExprs(),
245 ParenList->getNumExprs(),
246 TemplateArgs, CommaLocs,
247 NewArgs);
248 }
249
250 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
251 if (InstantiateInitializationArguments(S,
252 Construct->getArgs(),
253 Construct->getNumArgs(),
254 TemplateArgs,
255 CommaLocs, NewArgs))
256 return true;
257
258 // FIXME: Fake locations!
259 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
260 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
261 return false;
262 }
263
264 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
265 if (Result.isInvalid())
266 return true;
267
268 NewArgs.push_back(Result.takeAs<Expr>());
269 return false;
270}
271
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000272Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000273 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000274 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000275 TemplateArgs,
276 D->getTypeSpecStartLoc(),
277 D->getDeclName());
278 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000279 return 0;
280
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000281 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000282 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
283 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000284 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000285 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000286 Var->setThreadSpecified(D->isThreadSpecified());
287 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
288 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000289
290 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000291 // out-of-line, the instantiation will have the same lexical
292 // context (which will be a namespace scope) as the template.
293 if (D->isOutOfLine())
294 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000295
John McCall46460a62010-01-20 21:53:11 +0000296 Var->setAccess(D->getAccess());
297
Mike Stump390b4cc2009-05-16 07:39:55 +0000298 // FIXME: In theory, we could have a previous declaration for variables that
299 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000300 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000301 // FIXME: having to fake up a LookupResult is dumb.
302 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000303 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000304 if (D->isStaticDataMember())
305 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000306 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Douglas Gregor7caa6822009-07-24 20:34:43 +0000308 if (D->isOutOfLine()) {
309 D->getLexicalDeclContext()->addDecl(Var);
310 Owner->makeDeclVisibleInContext(Var);
311 } else {
312 Owner->addDecl(Var);
313 }
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000315 // Link instantiations of static data members back to the template from
316 // which they were instantiated.
317 if (Var->isStaticDataMember())
318 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000319 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000320
Douglas Gregor60c93c92010-02-09 07:26:29 +0000321 if (Var->getAnyInitializer()) {
322 // We already have an initializer in the class.
323 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000324 if (Var->isStaticDataMember() && !D->isOutOfLine())
325 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
326 else
327 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
328
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000329 // Instantiate the initializer.
330 SourceLocation LParenLoc, RParenLoc;
331 llvm::SmallVector<SourceLocation, 4> CommaLocs;
332 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
333 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
334 CommaLocs, InitArgs, RParenLoc)) {
335 // Attach the initializer to the declaration.
336 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000337 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000338 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000339 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000340 move_arg(InitArgs),
341 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000342 RParenLoc);
343 } else if (InitArgs.size() == 1) {
344 Expr *Init = (Expr*)(InitArgs.take()[0]);
345 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
346 SemaRef.Owned(Init),
347 false);
348 } else {
349 assert(InitArgs.size() == 0);
350 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000351 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000352 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 // FIXME: Not too happy about invalidating the declaration
354 // because of a bogus initializer.
355 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000356 }
357
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000358 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000359 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
360 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000361
362 return Var;
363}
364
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000365Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
366 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000367 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000368 if (DI->getType()->isDependentType()) {
369 DI = SemaRef.SubstType(DI, TemplateArgs,
370 D->getLocation(), D->getDeclName());
371 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000372 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000373 Invalid = true;
374 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 // C++ [temp.arg.type]p3:
376 // If a declaration acquires a function type through a type
377 // dependent on a template-parameter and this causes a
378 // declaration that does not use the syntactic form of a
379 // function declarator to have function type, the program is
380 // ill-formed.
381 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000382 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383 Invalid = true;
384 }
385 }
386
387 Expr *BitWidth = D->getBitWidth();
388 if (Invalid)
389 BitWidth = 0;
390 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000391 // The bit-width expression is not potentially evaluated.
392 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000394 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000395 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000396 if (InstantiatedBitWidth.isInvalid()) {
397 Invalid = true;
398 BitWidth = 0;
399 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000400 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 }
402
John McCall07fb6be2009-10-22 23:33:21 +0000403 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
404 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000405 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000406 D->getLocation(),
407 D->isMutable(),
408 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000409 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000410 D->getAccess(),
411 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000412 if (!Field) {
413 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000414 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000417 InstantiateAttrs(D, Field);
418
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000419 if (Invalid)
420 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000422 if (!Field->getDeclName()) {
423 // Keep track of where this decl came from.
424 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000427 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000428 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000429 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430
431 return Field;
432}
433
John McCall02cace72009-08-28 07:59:38 +0000434Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
435 FriendDecl::FriendUnion FU;
436
437 // Handle friend type expressions by simply substituting template
438 // parameters into the pattern type.
439 if (Type *Ty = D->getFriendType()) {
440 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
441 D->getLocation(), DeclarationName());
442 if (T.isNull()) return 0;
443
444 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
445 FU = T.getTypePtr();
446
447 // Handle everything else by appropriate substitution.
448 } else {
449 NamedDecl *ND = D->getFriendDecl();
450 assert(ND && "friend decl must be a decl or a type!");
451
Douglas Gregora735b202009-10-13 14:39:41 +0000452 // FIXME: We have a problem here, because the nested call to Visit(ND)
453 // will inject the thing that the friend references into the current
454 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000455 Decl *NewND;
456
457 // Hack to make this work almost well pending a rewrite.
Douglas Gregor63644fa2010-02-07 10:31:35 +0000458 if (ND->getDeclContext()->isRecord()) {
459 if (!ND->getDeclContext()->isDependentContext()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000460 NewND = SemaRef.FindInstantiatedDecl(D->getLocation(), ND,
461 TemplateArgs);
Douglas Gregor63644fa2010-02-07 10:31:35 +0000462 } else {
463 // FIXME: Hack to avoid crashing when incorrectly trying to instantiate
464 // templated friend declarations. This doesn't produce a correct AST;
465 // however this is sufficient for some AST analysis. The real solution
466 // must be put in place during the pending rewrite. See PR5848.
467 return 0;
468 }
469 } else if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000470 // Totally egregious hack to work around PR5866
471 return 0;
472 } else
John McCalle129d442009-12-17 23:21:11 +0000473 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000474 if (!NewND) return 0;
475
476 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
John McCall02cace72009-08-28 07:59:38 +0000479 FriendDecl *FD =
480 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
481 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000482 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000483 Owner->addDecl(FD);
484 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000485}
486
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000487Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
488 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregorac7610d2009-06-22 20:57:11 +0000490 // The expression in a static assertion is not potentially evaluated.
491 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000493 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000494 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000495 if (InstantiatedAssertExpr.isInvalid())
496 return 0;
497
Douglas Gregor43d9d922009-08-08 01:41:12 +0000498 OwningExprResult Message(SemaRef, D->getMessage());
499 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000500 Decl *StaticAssert
501 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000502 move(InstantiatedAssertExpr),
503 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000504 return StaticAssert;
505}
506
507Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000508 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000509 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000510 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000511 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000512 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000513 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000514 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000515 Enum->startDefinition();
516
Douglas Gregor96084f12010-03-01 19:00:07 +0000517 if (D->getDeclContext()->isFunctionOrMethod())
518 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
519
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000520 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000521
522 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000523 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
524 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000525 EC != ECEnd; ++EC) {
526 // The specified value for the enumerator.
527 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000528 if (Expr *UninstValue = EC->getInitExpr()) {
529 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000530 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000531 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000532
John McCallce3ff2b2009-08-25 22:02:44 +0000533 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000534 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535
536 // Drop the initial value and continue.
537 bool isInvalid = false;
538 if (Value.isInvalid()) {
539 Value = SemaRef.Owned((Expr *)0);
540 isInvalid = true;
541 }
542
Mike Stump1eb44332009-09-09 15:08:12 +0000543 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000544 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
545 EC->getLocation(), EC->getIdentifier(),
546 move(Value));
547
548 if (isInvalid) {
549 if (EnumConst)
550 EnumConst->setInvalidDecl();
551 Enum->setInvalidDecl();
552 }
553
554 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000555 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000556 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000557 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000558 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000559
560 if (D->getDeclContext()->isFunctionOrMethod()) {
561 // If the enumeration is within a function or method, record the enum
562 // constant as a local.
563 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
564 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000565 }
566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000568 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000569 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000570 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
571 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000572 &Enumerators[0], Enumerators.size(),
573 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000574
575 return Enum;
576}
577
Douglas Gregor6477b692009-03-25 15:04:13 +0000578Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
579 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
580 return 0;
581}
582
Douglas Gregored9c0f92009-10-29 00:04:11 +0000583namespace {
584 class SortDeclByLocation {
585 SourceManager &SourceMgr;
586
587 public:
588 explicit SortDeclByLocation(SourceManager &SourceMgr)
589 : SourceMgr(SourceMgr) { }
590
591 bool operator()(const Decl *X, const Decl *Y) const {
592 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
593 Y->getLocation());
594 }
595 };
596}
597
John McCalle29ba202009-08-20 01:44:21 +0000598Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000599 // Create a local instantiation scope for this class template, which
600 // will contain the instantiations of the template parameters.
601 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000602 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000603 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000604 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000605 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000606
607 CXXRecordDecl *Pattern = D->getTemplatedDecl();
608 CXXRecordDecl *RecordInst
609 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
610 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000611 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
612 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000613
614 ClassTemplateDecl *Inst
615 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
616 D->getIdentifier(), InstParams, RecordInst, 0);
617 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000618 if (D->getFriendObjectKind())
619 Inst->setObjectOfFriendDecl(true);
620 else
621 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000622 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000623
624 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000625 SemaRef.Context.getInjectedClassNameType(RecordInst,
626 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
Douglas Gregorf0510d42009-10-12 23:11:44 +0000627
Douglas Gregor259571e2009-10-30 22:42:42 +0000628 // Finish handling of friends.
629 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000630 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000631 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000632
John McCall46460a62010-01-20 21:53:11 +0000633 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000634 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000635
636 // First, we sort the partial specializations by location, so
637 // that we instantiate them in the order they were declared.
638 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
639 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
640 P = D->getPartialSpecializations().begin(),
641 PEnd = D->getPartialSpecializations().end();
642 P != PEnd; ++P)
643 PartialSpecs.push_back(&*P);
644 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
645 SortDeclByLocation(SemaRef.SourceMgr));
646
647 // Instantiate all of the partial specializations of this member class
648 // template.
649 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
650 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
651
John McCalle29ba202009-08-20 01:44:21 +0000652 return Inst;
653}
654
Douglas Gregord60e1052009-08-27 16:57:43 +0000655Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000656TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
657 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000658 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
659
660 // Lookup the already-instantiated declaration in the instantiation
661 // of the class template and return that.
662 DeclContext::lookup_result Found
663 = Owner->lookup(ClassTemplate->getDeclName());
664 if (Found.first == Found.second)
665 return 0;
666
667 ClassTemplateDecl *InstClassTemplate
668 = dyn_cast<ClassTemplateDecl>(*Found.first);
669 if (!InstClassTemplate)
670 return 0;
671
672 Decl *DCanon = D->getCanonicalDecl();
673 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
674 P = InstClassTemplate->getPartialSpecializations().begin(),
675 PEnd = InstClassTemplate->getPartialSpecializations().end();
676 P != PEnd; ++P) {
677 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
678 return &*P;
679 }
680
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000681 return 0;
682}
683
684Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000685TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000686 // Create a local instantiation scope for this function template, which
687 // will contain the instantiations of the template parameters and then get
688 // merged with the local instantiation scope for the function template
689 // itself.
690 Sema::LocalInstantiationScope Scope(SemaRef);
691
Douglas Gregord60e1052009-08-27 16:57:43 +0000692 TemplateParameterList *TempParams = D->getTemplateParameters();
693 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000694 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000695 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000696
Douglas Gregora735b202009-10-13 14:39:41 +0000697 FunctionDecl *Instantiated = 0;
698 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
699 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
700 InstParams));
701 else
702 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
703 D->getTemplatedDecl(),
704 InstParams));
705
706 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000707 return 0;
708
John McCall46460a62010-01-20 21:53:11 +0000709 Instantiated->setAccess(D->getAccess());
710
Mike Stump1eb44332009-09-09 15:08:12 +0000711 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000712 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000713 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000714 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000715 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000716 assert(InstTemplate &&
717 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000718
719 // Link the instantiation back to the pattern *unless* this is a
720 // non-definition friend declaration.
721 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
722 !(InstTemplate->getFriendObjectKind() &&
723 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000724 InstTemplate->setInstantiatedFromMemberTemplate(D);
725
726 // Add non-friends into the owner.
727 if (!InstTemplate->getFriendObjectKind())
728 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000729 return InstTemplate;
730}
731
Douglas Gregord475b8d2009-03-25 21:17:03 +0000732Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
733 CXXRecordDecl *PrevDecl = 0;
734 if (D->isInjectedClassName())
735 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000736 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000737 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
738 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000739 TemplateArgs);
740 if (!Prev) return 0;
741 PrevDecl = cast<CXXRecordDecl>(Prev);
742 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000743
744 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000745 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000746 D->getLocation(), D->getIdentifier(),
747 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000748 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000749 // FIXME: Check against AS_none is an ugly hack to work around the issue that
750 // the tag decls introduced by friend class declarations don't have an access
751 // specifier. Remove once this area of the code gets sorted out.
752 if (D->getAccess() != AS_none)
753 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000754 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000755 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000756
John McCall02cace72009-08-28 07:59:38 +0000757 // If the original function was part of a friend declaration,
758 // inherit its namespace state.
759 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
760 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
761
Anders Carlssond8b285f2009-09-01 04:26:58 +0000762 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
763
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000764 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000765 return Record;
766}
767
John McCall02cace72009-08-28 07:59:38 +0000768/// Normal class members are of more specific types and therefore
769/// don't make it here. This function serves two purposes:
770/// 1) instantiating function templates
771/// 2) substituting friend declarations
772/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000773Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000774 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000775 // Check whether there is already a function template specialization for
776 // this declaration.
777 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
778 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000779 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000780 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000781 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000782 TemplateArgs.getInnermost().getFlatArgumentList(),
783 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000784 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
786 FunctionTemplateSpecializationInfo *Info
787 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000788 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Douglas Gregor127102b2009-06-29 20:59:39 +0000790 // If we already have a function template specialization, return it.
791 if (Info)
792 return Info->Function;
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregor79c22782010-01-16 20:21:20 +0000795 bool MergeWithParentScope = (TemplateParams != 0) ||
796 !(isa<Decl>(Owner) &&
797 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
798 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregore53060f2009-06-25 22:08:12 +0000800 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000801 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
802 TInfo = SubstFunctionType(D, Params);
803 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000804 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000805 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000806
John McCall68b6b872010-02-06 01:50:47 +0000807 // If we're instantiating a local function declaration, put the result
808 // in the owner; otherwise we need to find the instantiated context.
809 DeclContext *DC;
810 if (D->getDeclContext()->isFunctionOrMethod())
811 DC = Owner;
812 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000813 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
814 TemplateArgs);
John McCall68b6b872010-02-06 01:50:47 +0000815
John McCall02cace72009-08-28 07:59:38 +0000816 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000817 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000818 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000819 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000820 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000821 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregore53060f2009-06-25 22:08:12 +0000823 // Attach the parameters
824 for (unsigned P = 0; P < Params.size(); ++P)
825 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000826 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000827
Douglas Gregora735b202009-10-13 14:39:41 +0000828 if (TemplateParams) {
829 // Our resulting instantiation is actually a function template, since we
830 // are substituting only the outer template parameters. For example, given
831 //
832 // template<typename T>
833 // struct X {
834 // template<typename U> friend void f(T, U);
835 // };
836 //
837 // X<int> x;
838 //
839 // We are instantiating the friend function template "f" within X<int>,
840 // which means substituting int for T, but leaving "f" as a friend function
841 // template.
842 // Build the function template itself.
843 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
844 Function->getLocation(),
845 Function->getDeclName(),
846 TemplateParams, Function);
847 Function->setDescribedFunctionTemplate(FunctionTemplate);
848 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000849 } else if (FunctionTemplate) {
850 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000851 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000852 &TemplateArgs.getInnermost(),
853 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000854 }
Douglas Gregora735b202009-10-13 14:39:41 +0000855
Douglas Gregore53060f2009-06-25 22:08:12 +0000856 if (InitFunctionInstantiation(Function, D))
857 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregore53060f2009-06-25 22:08:12 +0000859 bool Redeclaration = false;
860 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000861
John McCall68263142009-11-18 22:49:29 +0000862 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
863 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
864
Douglas Gregora735b202009-10-13 14:39:41 +0000865 if (TemplateParams || !FunctionTemplate) {
866 // Look only into the namespace where the friend would be declared to
867 // find a previous declaration. This is the innermost enclosing namespace,
868 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000869 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000870
Douglas Gregora735b202009-10-13 14:39:41 +0000871 // In C++, the previous declaration we find might be a tag type
872 // (class or enum). In this case, the new declaration will hide the
873 // tag type. Note that this does does not apply if we're declaring a
874 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000875 if (Previous.isSingleTagDecl())
876 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000877 }
878
John McCall9f54ad42009-12-10 09:41:52 +0000879 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
880 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000881 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000882
Douglas Gregora735b202009-10-13 14:39:41 +0000883 // If the original function was part of a friend declaration,
884 // inherit its namespace state and add it to the owner.
885 NamedDecl *FromFriendD
886 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
887 if (FromFriendD->getFriendObjectKind()) {
888 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000889 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000890 if (TemplateParams) {
891 ToFriendD = cast<NamedDecl>(FunctionTemplate);
892 PrevDecl = FunctionTemplate->getPreviousDeclaration();
893 } else {
894 ToFriendD = Function;
895 PrevDecl = Function->getPreviousDeclaration();
896 }
897 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
898 if (!Owner->isDependentContext() && !PrevDecl)
899 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
900
901 if (!TemplateParams)
902 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
903 }
904
Douglas Gregore53060f2009-06-25 22:08:12 +0000905 return Function;
906}
907
Douglas Gregord60e1052009-08-27 16:57:43 +0000908Decl *
909TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
910 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000911 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
912 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000913 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000914 // We are creating a function template specialization from a function
915 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000916 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000917 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000918 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000919 TemplateArgs.getInnermost().getFlatArgumentList(),
920 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000921 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
923 FunctionTemplateSpecializationInfo *Info
924 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000925 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Douglas Gregor6b906862009-08-21 00:16:32 +0000927 // If we already have a function template specialization, return it.
928 if (Info)
929 return Info->Function;
930 }
931
Douglas Gregor79c22782010-01-16 20:21:20 +0000932 bool MergeWithParentScope = (TemplateParams != 0) ||
933 !(isa<Decl>(Owner) &&
934 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
935 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000936
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000937 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000938 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
939 TInfo = SubstFunctionType(D, Params);
940 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000941 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000942 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000943
944 // Build the instantiated method declaration.
945 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000946 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregordec06662009-08-21 18:42:58 +0000948 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000949 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000950 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
951 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
952 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000953 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
954 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000955 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +0000956 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000957 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000958 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
959 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
960 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
961 SemaRef.Context.getCanonicalType(ClassTy));
962 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
963 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000964 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000965 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000966 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000967 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000968 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000969 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
970 ConvTy);
971 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
972 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +0000973 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000974 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000975 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000976 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000977 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000978 D->getDeclName(), T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000979 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000980 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000981
Douglas Gregord60e1052009-08-27 16:57:43 +0000982 if (TemplateParams) {
983 // Our resulting instantiation is actually a function template, since we
984 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000985 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000986 // template<typename T>
987 // struct X {
988 // template<typename U> void f(T, U);
989 // };
990 //
991 // X<int> x;
992 //
993 // We are instantiating the member template "f" within X<int>, which means
994 // substituting int for T, but leaving "f" as a member function template.
995 // Build the function template itself.
996 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
997 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000998 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000999 TemplateParams, Method);
1000 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001001 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001002 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001003 } else if (FunctionTemplate) {
1004 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001005 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001006 &TemplateArgs.getInnermost(),
1007 InsertPos);
1008 } else {
1009 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001010 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001011 }
1012
Mike Stump1eb44332009-09-09 15:08:12 +00001013 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001014 // out-of-line, the instantiation will have the same lexical
1015 // context (which will be a namespace scope) as the template.
1016 if (D->isOutOfLine())
1017 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Douglas Gregor5545e162009-03-24 00:38:23 +00001019 // Attach the parameters
1020 for (unsigned P = 0; P < Params.size(); ++P)
1021 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001022 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001023
1024 if (InitMethodInstantiation(Method, D))
1025 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001026
John McCall68263142009-11-18 22:49:29 +00001027 LookupResult Previous(SemaRef, Name, SourceLocation(),
1028 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregord60e1052009-08-27 16:57:43 +00001030 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +00001031 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregordec06662009-08-21 18:42:58 +00001033 // In C++, the previous declaration we find might be a tag type
1034 // (class or enum). In this case, the new declaration will hide the
1035 // tag type. Note that this does does not apply if we're declaring a
1036 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001037 if (Previous.isSingleTagDecl())
1038 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001039 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001040
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001041 bool Redeclaration = false;
1042 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001043 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001044 /*FIXME:*/OverloadableAttrRequired);
1045
Douglas Gregor4ba31362009-12-01 17:24:26 +00001046 if (D->isPure())
1047 SemaRef.CheckPureMethod(Method, SourceRange());
1048
John McCall46460a62010-01-20 21:53:11 +00001049 Method->setAccess(D->getAccess());
1050
John McCall68263142009-11-18 22:49:29 +00001051 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +00001052 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +00001053 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001055 return Method;
1056}
1057
Douglas Gregor615c5d42009-03-24 16:43:20 +00001058Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001059 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001060}
1061
Douglas Gregor03b2b072009-03-24 00:15:49 +00001062Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001063 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001064}
1065
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001066Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001067 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001068}
1069
Douglas Gregor6477b692009-03-25 15:04:13 +00001070ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001071 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001072 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001073 if (DI) {
1074 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1075 D->getDeclName());
1076 if (DI) T = DI->getType();
1077 } else {
1078 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1079 D->getDeclName());
1080 DI = 0;
1081 }
1082
1083 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001084 return 0;
1085
John McCall58e46772009-10-23 21:48:59 +00001086 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001087
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001088 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001089 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001090 = ParmVarDecl::Create(SemaRef.Context,
1091 SemaRef.Context.getTranslationUnitDecl(),
1092 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001093 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001094
Anders Carlsson9351c172009-08-25 03:18:48 +00001095 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001096 if (D->hasUninstantiatedDefaultArg())
1097 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001098 else if (Expr *Arg = D->getDefaultArg())
1099 Param->setUninstantiatedDefaultArg(Arg);
1100
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001101 // Note: we don't try to instantiate function parameters until after
1102 // we've instantiated the function's type. Therefore, we don't have
1103 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001104 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001105 return Param;
1106}
1107
John McCalle29ba202009-08-20 01:44:21 +00001108Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1109 TemplateTypeParmDecl *D) {
1110 // TODO: don't always clone when decls are refcounted.
1111 const Type* T = D->getTypeForDecl();
1112 assert(T->isTemplateTypeParmType());
1113 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001114
John McCalle29ba202009-08-20 01:44:21 +00001115 TemplateTypeParmDecl *Inst =
1116 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001117 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001118 TTPT->getName(),
1119 D->wasDeclaredWithTypename(),
1120 D->isParameterPack());
1121
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001122 if (D->hasDefaultArgument())
1123 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001124
Douglas Gregor550d9b22009-10-31 17:21:17 +00001125 // Introduce this template parameter's instantiation into the instantiation
1126 // scope.
1127 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1128
John McCalle29ba202009-08-20 01:44:21 +00001129 return Inst;
1130}
1131
Douglas Gregor33642df2009-10-23 23:25:44 +00001132Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1133 NonTypeTemplateParmDecl *D) {
1134 // Substitute into the type of the non-type template parameter.
1135 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001136 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001137 if (DI) {
1138 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1139 D->getDeclName());
1140 if (DI) T = DI->getType();
1141 } else {
1142 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1143 D->getDeclName());
1144 DI = 0;
1145 }
1146 if (T.isNull())
1147 return 0;
1148
1149 // Check that this type is acceptable for a non-type template parameter.
1150 bool Invalid = false;
1151 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1152 if (T.isNull()) {
1153 T = SemaRef.Context.IntTy;
1154 Invalid = true;
1155 }
1156
1157 NonTypeTemplateParmDecl *Param
1158 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1159 D->getDepth() - 1, D->getPosition(),
1160 D->getIdentifier(), T, DI);
1161 if (Invalid)
1162 Param->setInvalidDecl();
1163
1164 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001165
1166 // Introduce this template parameter's instantiation into the instantiation
1167 // scope.
1168 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001169 return Param;
1170}
1171
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001172Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001173TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1174 TemplateTemplateParmDecl *D) {
1175 // Instantiate the template parameter list of the template template parameter.
1176 TemplateParameterList *TempParams = D->getTemplateParameters();
1177 TemplateParameterList *InstParams;
1178 {
1179 // Perform the actual substitution of template parameters within a new,
1180 // local instantiation scope.
1181 Sema::LocalInstantiationScope Scope(SemaRef);
1182 InstParams = SubstTemplateParams(TempParams);
1183 if (!InstParams)
1184 return NULL;
1185 }
1186
1187 // Build the template template parameter.
1188 TemplateTemplateParmDecl *Param
1189 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1190 D->getDepth() - 1, D->getPosition(),
1191 D->getIdentifier(), InstParams);
1192 Param->setDefaultArgument(D->getDefaultArgument());
1193
1194 // Introduce this template parameter's instantiation into the instantiation
1195 // scope.
1196 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1197
1198 return Param;
1199}
1200
Douglas Gregor48c32a72009-11-17 06:07:40 +00001201Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1202 // Using directives are never dependent, so they require no explicit
1203
1204 UsingDirectiveDecl *Inst
1205 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1206 D->getNamespaceKeyLocation(),
1207 D->getQualifierRange(), D->getQualifier(),
1208 D->getIdentLocation(),
1209 D->getNominatedNamespace(),
1210 D->getCommonAncestor());
1211 Owner->addDecl(Inst);
1212 return Inst;
1213}
1214
John McCalled976492009-12-04 22:46:56 +00001215Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1216 // The nested name specifier is non-dependent, so no transformation
1217 // is required.
1218
John McCall9f54ad42009-12-10 09:41:52 +00001219 // We only need to do redeclaration lookups if we're in a class
1220 // scope (in fact, it's not really even possible in non-class
1221 // scopes).
1222 bool CheckRedeclaration = Owner->isRecord();
1223
1224 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1225 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1226
John McCalled976492009-12-04 22:46:56 +00001227 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1228 D->getLocation(),
1229 D->getNestedNameRange(),
1230 D->getUsingLocation(),
1231 D->getTargetNestedNameDecl(),
1232 D->getDeclName(),
1233 D->isTypeName());
1234
1235 CXXScopeSpec SS;
1236 SS.setScopeRep(D->getTargetNestedNameDecl());
1237 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001238
1239 if (CheckRedeclaration) {
1240 Prev.setHideTags(false);
1241 SemaRef.LookupQualifiedName(Prev, Owner);
1242
1243 // Check for invalid redeclarations.
1244 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1245 D->isTypeName(), SS,
1246 D->getLocation(), Prev))
1247 NewUD->setInvalidDecl();
1248
1249 }
1250
1251 if (!NewUD->isInvalidDecl() &&
1252 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001253 D->getLocation()))
1254 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001255
John McCalled976492009-12-04 22:46:56 +00001256 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1257 NewUD->setAccess(D->getAccess());
1258 Owner->addDecl(NewUD);
1259
John McCall9f54ad42009-12-10 09:41:52 +00001260 // Don't process the shadow decls for an invalid decl.
1261 if (NewUD->isInvalidDecl())
1262 return NewUD;
1263
John McCall323c3102009-12-22 22:26:37 +00001264 bool isFunctionScope = Owner->isFunctionOrMethod();
1265
John McCall9f54ad42009-12-10 09:41:52 +00001266 // Process the shadow decls.
1267 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1268 I != E; ++I) {
1269 UsingShadowDecl *Shadow = *I;
1270 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001271 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1272 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001273 TemplateArgs));
1274
1275 if (CheckRedeclaration &&
1276 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1277 continue;
1278
1279 UsingShadowDecl *InstShadow
1280 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1281 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001282
1283 if (isFunctionScope)
1284 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001285 }
John McCalled976492009-12-04 22:46:56 +00001286
1287 return NewUD;
1288}
1289
1290Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001291 // Ignore these; we handle them in bulk when processing the UsingDecl.
1292 return 0;
John McCalled976492009-12-04 22:46:56 +00001293}
1294
John McCall7ba107a2009-11-18 02:36:19 +00001295Decl * TemplateDeclInstantiator
1296 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001297 NestedNameSpecifier *NNS =
1298 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1299 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001300 TemplateArgs);
1301 if (!NNS)
1302 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001304 CXXScopeSpec SS;
1305 SS.setRange(D->getTargetNestedNameRange());
1306 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001307
1308 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001309 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001310 D->getUsingLoc(), SS, D->getLocation(),
1311 D->getDeclName(), 0,
1312 /*instantiation*/ true,
1313 /*typename*/ true, D->getTypenameLoc());
1314 if (UD)
John McCalled976492009-12-04 22:46:56 +00001315 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1316
John McCall7ba107a2009-11-18 02:36:19 +00001317 return UD;
1318}
1319
1320Decl * TemplateDeclInstantiator
1321 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1322 NestedNameSpecifier *NNS =
1323 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1324 D->getTargetNestedNameRange(),
1325 TemplateArgs);
1326 if (!NNS)
1327 return 0;
1328
1329 CXXScopeSpec SS;
1330 SS.setRange(D->getTargetNestedNameRange());
1331 SS.setScopeRep(NNS);
1332
1333 NamedDecl *UD =
1334 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1335 D->getUsingLoc(), SS, D->getLocation(),
1336 D->getDeclName(), 0,
1337 /*instantiation*/ true,
1338 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001339 if (UD)
John McCalled976492009-12-04 22:46:56 +00001340 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1341
Anders Carlsson0d8df782009-08-29 19:37:28 +00001342 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001343}
1344
John McCallce3ff2b2009-08-25 22:02:44 +00001345Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001346 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001347 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001348 if (D->isInvalidDecl())
1349 return 0;
1350
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001351 return Instantiator.Visit(D);
1352}
1353
John McCalle29ba202009-08-20 01:44:21 +00001354/// \brief Instantiates a nested template parameter list in the current
1355/// instantiation context.
1356///
1357/// \param L The parameter list to instantiate
1358///
1359/// \returns NULL if there was an error
1360TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001361TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001362 // Get errors for all the parameters before bailing out.
1363 bool Invalid = false;
1364
1365 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001366 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001367 ParamVector Params;
1368 Params.reserve(N);
1369 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1370 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001371 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001372 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001373 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001374 }
1375
1376 // Clean up if we had an error.
1377 if (Invalid) {
1378 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1379 PI != PE; ++PI)
1380 if (*PI)
1381 (*PI)->Destroy(SemaRef.Context);
1382 return NULL;
1383 }
1384
1385 TemplateParameterList *InstL
1386 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1387 L->getLAngleLoc(), &Params.front(), N,
1388 L->getRAngleLoc());
1389 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001390}
John McCalle29ba202009-08-20 01:44:21 +00001391
Douglas Gregored9c0f92009-10-29 00:04:11 +00001392/// \brief Instantiate the declaration of a class template partial
1393/// specialization.
1394///
1395/// \param ClassTemplate the (instantiated) class template that is partially
1396// specialized by the instantiation of \p PartialSpec.
1397///
1398/// \param PartialSpec the (uninstantiated) class template partial
1399/// specialization that we are instantiating.
1400///
1401/// \returns true if there was an error, false otherwise.
1402bool
1403TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1404 ClassTemplateDecl *ClassTemplate,
1405 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001406 // Create a local instantiation scope for this class template partial
1407 // specialization, which will contain the instantiations of the template
1408 // parameters.
1409 Sema::LocalInstantiationScope Scope(SemaRef);
1410
Douglas Gregored9c0f92009-10-29 00:04:11 +00001411 // Substitute into the template parameters of the class template partial
1412 // specialization.
1413 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1414 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1415 if (!InstParams)
1416 return true;
1417
1418 // Substitute into the template arguments of the class template partial
1419 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001420 const TemplateArgumentLoc *PartialSpecTemplateArgs
1421 = PartialSpec->getTemplateArgsAsWritten();
1422 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1423
John McCalld5532b62009-11-23 01:53:49 +00001424 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001425 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001426 TemplateArgumentLoc Loc;
1427 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001428 return true;
John McCalld5532b62009-11-23 01:53:49 +00001429 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001430 }
1431
1432
1433 // Check that the template argument list is well-formed for this
1434 // class template.
1435 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1436 InstTemplateArgs.size());
1437 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1438 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001439 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001440 false,
1441 Converted))
1442 return true;
1443
1444 // Figure out where to insert this class template partial specialization
1445 // in the member template's set of class template partial specializations.
1446 llvm::FoldingSetNodeID ID;
1447 ClassTemplatePartialSpecializationDecl::Profile(ID,
1448 Converted.getFlatArguments(),
1449 Converted.flatSize(),
1450 SemaRef.Context);
1451 void *InsertPos = 0;
1452 ClassTemplateSpecializationDecl *PrevDecl
1453 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1454 InsertPos);
1455
1456 // Build the canonical type that describes the converted template
1457 // arguments of the class template partial specialization.
1458 QualType CanonType
1459 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1460 Converted.getFlatArguments(),
1461 Converted.flatSize());
1462
1463 // Build the fully-sugared type for this class template
1464 // specialization as the user wrote in the specialization
1465 // itself. This means that we'll pretty-print the type retrieved
1466 // from the specialization's declaration the way that the user
1467 // actually wrote the specialization, rather than formatting the
1468 // name based on the "canonical" representation used to store the
1469 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001470 TypeSourceInfo *WrittenTy
1471 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1472 TemplateName(ClassTemplate),
1473 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001474 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001475 CanonType);
1476
1477 if (PrevDecl) {
1478 // We've already seen a partial specialization with the same template
1479 // parameters and template arguments. This can happen, for example, when
1480 // substituting the outer template arguments ends up causing two
1481 // class template partial specializations of a member class template
1482 // to have identical forms, e.g.,
1483 //
1484 // template<typename T, typename U>
1485 // struct Outer {
1486 // template<typename X, typename Y> struct Inner;
1487 // template<typename Y> struct Inner<T, Y>;
1488 // template<typename Y> struct Inner<U, Y>;
1489 // };
1490 //
1491 // Outer<int, int> outer; // error: the partial specializations of Inner
1492 // // have the same signature.
1493 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1494 << WrittenTy;
1495 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1496 << SemaRef.Context.getTypeDeclType(PrevDecl);
1497 return true;
1498 }
1499
1500
1501 // Create the class template partial specialization declaration.
1502 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1503 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1504 PartialSpec->getLocation(),
1505 InstParams,
1506 ClassTemplate,
1507 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001508 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001509 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001510 0);
1511 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1512 InstPartialSpec->setTypeAsWritten(WrittenTy);
1513
1514 // Add this partial specialization to the set of class template partial
1515 // specializations.
1516 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1517 InsertPos);
1518 return false;
1519}
1520
John McCall21ef0fa2010-03-11 09:03:00 +00001521bool
1522Sema::CheckInstantiatedParams(llvm::SmallVectorImpl<ParmVarDecl*> &Params) {
1523 bool Invalid = false;
1524 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
1525 if (ParmVarDecl *PInst = Params[i]) {
1526 if (PInst->isInvalidDecl())
1527 Invalid = true;
1528 else if (PInst->getType()->isVoidType()) {
1529 Diag(PInst->getLocation(), diag::err_param_with_void_type);
1530 PInst->setInvalidDecl();
1531 Invalid = true;
1532 }
1533 else if (RequireNonAbstractType(PInst->getLocation(),
1534 PInst->getType(),
1535 diag::err_abstract_type_in_decl,
1536 Sema::AbstractParamType)) {
1537 PInst->setInvalidDecl();
1538 Invalid = true;
1539 }
1540 }
1541 return Invalid;
1542}
Douglas Gregor5545e162009-03-24 00:38:23 +00001543
John McCall21ef0fa2010-03-11 09:03:00 +00001544TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001545TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001546 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001547 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1548 assert(OldTInfo && "substituting function without type source info");
1549 assert(Params.empty() && "parameter vector is non-empty at start");
1550 TypeSourceInfo *NewTInfo = SemaRef.SubstType(OldTInfo, TemplateArgs,
1551 D->getTypeSpecStartLoc(),
1552 D->getDeclName());
1553 if (!NewTInfo)
1554 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001555
John McCall21ef0fa2010-03-11 09:03:00 +00001556 // Get parameters from the new type info.
1557 TypeLoc NewTL = NewTInfo->getTypeLoc();
1558 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1559 assert(NewProtoLoc && "Missing prototype?");
1560 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1561 Params.push_back(NewProtoLoc->getArg(i));
Douglas Gregor5545e162009-03-24 00:38:23 +00001562
John McCall21ef0fa2010-03-11 09:03:00 +00001563 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001564}
1565
Mike Stump1eb44332009-09-09 15:08:12 +00001566/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001567/// declaration (New) from the corresponding fields of its template (Tmpl).
1568///
1569/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001570bool
1571TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001572 FunctionDecl *Tmpl) {
1573 if (Tmpl->isDeleted())
1574 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregorcca9e962009-07-01 22:01:06 +00001576 // If we are performing substituting explicitly-specified template arguments
1577 // or deduced template arguments into a function template and we reach this
1578 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // to keeping the new function template specialization. We therefore
1580 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001581 // into a template instantiation for this specific function template
1582 // specialization, which is not a SFINAE context, so that we diagnose any
1583 // further errors in the declaration itself.
1584 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1585 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1586 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1587 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001588 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001589 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001590 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001591 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001592 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001593 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1594 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001595 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001596 }
1597 }
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001599 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1600 assert(Proto && "Function template without prototype?");
1601
1602 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1603 Proto->getNoReturnAttr()) {
1604 // The function has an exception specification or a "noreturn"
1605 // attribute. Substitute into each of the exception types.
1606 llvm::SmallVector<QualType, 4> Exceptions;
1607 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1608 // FIXME: Poor location information!
1609 QualType T
1610 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1611 New->getLocation(), New->getDeclName());
1612 if (T.isNull() ||
1613 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1614 continue;
1615
1616 Exceptions.push_back(T);
1617 }
1618
1619 // Rebuild the function type
1620
1621 const FunctionProtoType *NewProto
1622 = New->getType()->getAs<FunctionProtoType>();
1623 assert(NewProto && "Template instantiation without function prototype?");
1624 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1625 NewProto->arg_type_begin(),
1626 NewProto->getNumArgs(),
1627 NewProto->isVariadic(),
1628 NewProto->getTypeQuals(),
1629 Proto->hasExceptionSpec(),
1630 Proto->hasAnyExceptionSpec(),
1631 Exceptions.size(),
1632 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001633 Proto->getNoReturnAttr(),
1634 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001635 }
1636
Douglas Gregore53060f2009-06-25 22:08:12 +00001637 return false;
1638}
1639
Douglas Gregor5545e162009-03-24 00:38:23 +00001640/// \brief Initializes common fields of an instantiated method
1641/// declaration (New) from the corresponding fields of its template
1642/// (Tmpl).
1643///
1644/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001645bool
1646TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001647 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001648 if (InitFunctionInstantiation(New, Tmpl))
1649 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor5545e162009-03-24 00:38:23 +00001651 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1652 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001653 if (Tmpl->isVirtualAsWritten())
1654 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001655
1656 // FIXME: attributes
1657 // FIXME: New needs a pointer to Tmpl
1658 return false;
1659}
Douglas Gregora58861f2009-05-13 20:28:22 +00001660
1661/// \brief Instantiate the definition of the given function from its
1662/// template.
1663///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001664/// \param PointOfInstantiation the point at which the instantiation was
1665/// required. Note that this is not precisely a "point of instantiation"
1666/// for the function, but it's close.
1667///
Douglas Gregora58861f2009-05-13 20:28:22 +00001668/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001669/// function template specialization or member function of a class template
1670/// specialization.
1671///
1672/// \param Recursive if true, recursively instantiates any functions that
1673/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001674///
1675/// \param DefinitionRequired if true, then we are performing an explicit
1676/// instantiation where the body of the function is required. Complain if
1677/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001678void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001679 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001680 bool Recursive,
1681 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001682 if (Function->isInvalidDecl())
1683 return;
1684
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001685 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001687 // Never instantiate an explicit specialization.
1688 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1689 return;
1690
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001691 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001692 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001693 Stmt *Pattern = 0;
1694 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001695 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001696
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001697 if (!Pattern) {
1698 if (DefinitionRequired) {
1699 if (Function->getPrimaryTemplate())
1700 Diag(PointOfInstantiation,
1701 diag::err_explicit_instantiation_undefined_func_template)
1702 << Function->getPrimaryTemplate();
1703 else
1704 Diag(PointOfInstantiation,
1705 diag::err_explicit_instantiation_undefined_member)
1706 << 1 << Function->getDeclName() << Function->getDeclContext();
1707
1708 if (PatternDecl)
1709 Diag(PatternDecl->getLocation(),
1710 diag::note_explicit_instantiation_here);
1711 }
1712
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001713 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001714 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001715
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001716 // C++0x [temp.explicit]p9:
1717 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001719 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001720 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001721 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001722 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001723 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001725 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1726 if (Inst)
1727 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001728
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001729 // If we're performing recursive template instantiation, create our own
1730 // queue of pending implicit instantiations that we will instantiate later,
1731 // while we're still within our own instantiation context.
1732 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1733 if (Recursive)
1734 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001736 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1737
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001738 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001739 // recorded, unless we're actually a member function within a local
1740 // class, in which case we need to merge our results with the parent
1741 // scope (of the enclosing function).
1742 bool MergeWithParentScope = false;
1743 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1744 MergeWithParentScope = Rec->isLocalClass();
1745
1746 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001748 // Introduce the instantiated function parameters into the local
1749 // instantiation scope.
1750 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1751 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1752 Function->getParamDecl(I));
1753
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001754 // Enter the scope of this instantiation. We don't use
1755 // PushDeclContext because we don't have a scope.
1756 DeclContext *PreviousContext = CurContext;
1757 CurContext = Function;
1758
Mike Stump1eb44332009-09-09 15:08:12 +00001759 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001760 getTemplateInstantiationArgs(Function);
1761
1762 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001763 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001764 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1765 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1766 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001767 }
1768
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001769 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001770 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001771
Douglas Gregor52604ab2009-09-11 21:19:12 +00001772 if (Body.isInvalid())
1773 Function->setInvalidDecl();
1774
Mike Stump1eb44332009-09-09 15:08:12 +00001775 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001776 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001777
1778 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001779
1780 DeclGroupRef DG(Function);
1781 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor60406be2010-01-16 22:29:39 +00001783 // This class may have local implicit instantiations that need to be
1784 // instantiation within this scope.
1785 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1786 Scope.Exit();
1787
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001788 if (Recursive) {
1789 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001790 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001791 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001793 // Restore the set of pending implicit instantiations.
1794 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1795 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001796}
1797
1798/// \brief Instantiate the definition of the given variable from its
1799/// template.
1800///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001801/// \param PointOfInstantiation the point at which the instantiation was
1802/// required. Note that this is not precisely a "point of instantiation"
1803/// for the function, but it's close.
1804///
1805/// \param Var the already-instantiated declaration of a static member
1806/// variable of a class template specialization.
1807///
1808/// \param Recursive if true, recursively instantiates any functions that
1809/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001810///
1811/// \param DefinitionRequired if true, then we are performing an explicit
1812/// instantiation where an out-of-line definition of the member variable
1813/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001814void Sema::InstantiateStaticDataMemberDefinition(
1815 SourceLocation PointOfInstantiation,
1816 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001817 bool Recursive,
1818 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001819 if (Var->isInvalidDecl())
1820 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Douglas Gregor7caa6822009-07-24 20:34:43 +00001822 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001823 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001824 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001825 assert(Def->isStaticDataMember() && "Not a static data member?");
1826 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor0d035142009-10-27 18:42:08 +00001828 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001829 // We did not find an out-of-line definition of this static data member,
1830 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001831 // instantiate this definition (or provide a specialization for it) in
1832 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001833 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001834 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001835 Diag(PointOfInstantiation,
1836 diag::err_explicit_instantiation_undefined_member)
1837 << 2 << Var->getDeclName() << Var->getDeclContext();
1838 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1839 }
1840
Douglas Gregor7caa6822009-07-24 20:34:43 +00001841 return;
1842 }
1843
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001844 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001845 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001846 return;
1847
1848 // C++0x [temp.explicit]p9:
1849 // Except for inline functions, other explicit instantiation declarations
1850 // have the effect of suppressing the implicit instantiation of the entity
1851 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001852 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001853 == TSK_ExplicitInstantiationDeclaration)
1854 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregor7caa6822009-07-24 20:34:43 +00001856 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1857 if (Inst)
1858 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Douglas Gregor7caa6822009-07-24 20:34:43 +00001860 // If we're performing recursive template instantiation, create our own
1861 // queue of pending implicit instantiations that we will instantiate later,
1862 // while we're still within our own instantiation context.
1863 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1864 if (Recursive)
1865 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor7caa6822009-07-24 20:34:43 +00001867 // Enter the scope of this instantiation. We don't use
1868 // PushDeclContext because we don't have a scope.
1869 DeclContext *PreviousContext = CurContext;
1870 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001872 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001873 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001874 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001875 CurContext = PreviousContext;
1876
1877 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00001878 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1879 assert(MSInfo && "Missing member specialization information?");
1880 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1881 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001882 DeclGroupRef DG(Var);
1883 Consumer.HandleTopLevelDecl(DG);
1884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Douglas Gregor7caa6822009-07-24 20:34:43 +00001886 if (Recursive) {
1887 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001888 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001889 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregor7caa6822009-07-24 20:34:43 +00001891 // Restore the set of pending implicit instantiations.
1892 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001893 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001894}
Douglas Gregor815215d2009-05-27 05:35:12 +00001895
Anders Carlsson09025312009-08-29 05:16:22 +00001896void
1897Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1898 const CXXConstructorDecl *Tmpl,
1899 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Anders Carlsson09025312009-08-29 05:16:22 +00001901 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001902 bool AnyErrors = false;
1903
Anders Carlsson09025312009-08-29 05:16:22 +00001904 // Instantiate all the initializers.
1905 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001906 InitsEnd = Tmpl->init_end();
1907 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001908 CXXBaseOrMemberInitializer *Init = *Inits;
1909
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001910 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00001911 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001912 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001914 // Instantiate the initializer.
1915 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
1916 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
1917 AnyErrors = true;
1918 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00001919 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001920
Anders Carlsson09025312009-08-29 05:16:22 +00001921 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001922 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001923 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001924 TemplateArgs,
1925 Init->getSourceLocation(),
1926 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001927 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001928 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001929 New->setInvalidDecl();
1930 continue;
1931 }
1932
John McCalla93c9342009-12-07 02:54:59 +00001933 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001934 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001935 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001936 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001937 Init->getRParenLoc(),
1938 New->getParent());
1939 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001940 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001942 // Is this an anonymous union?
1943 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001944 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1945 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001946 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001947 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1948 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00001949 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001950
1951 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001952 NewArgs.size(),
1953 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001954 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001955 Init->getRParenLoc());
1956 }
1957
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001958 if (NewInit.isInvalid()) {
1959 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00001960 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001961 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00001962 // FIXME: It would be nice if ASTOwningVector had a release function.
1963 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Anders Carlsson09025312009-08-29 05:16:22 +00001965 NewInits.push_back((MemInitTy *)NewInit.get());
1966 }
1967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Anders Carlsson09025312009-08-29 05:16:22 +00001969 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001970 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001971 /*FIXME: ColonLoc */
1972 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001973 NewInits.data(), NewInits.size(),
1974 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00001975}
1976
John McCall52a575a2009-08-29 08:11:13 +00001977// TODO: this could be templated if the various decl types used the
1978// same method name.
1979static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1980 ClassTemplateDecl *Instance) {
1981 Pattern = Pattern->getCanonicalDecl();
1982
1983 do {
1984 Instance = Instance->getCanonicalDecl();
1985 if (Pattern == Instance) return true;
1986 Instance = Instance->getInstantiatedFromMemberTemplate();
1987 } while (Instance);
1988
1989 return false;
1990}
1991
Douglas Gregor0d696532009-09-28 06:34:35 +00001992static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1993 FunctionTemplateDecl *Instance) {
1994 Pattern = Pattern->getCanonicalDecl();
1995
1996 do {
1997 Instance = Instance->getCanonicalDecl();
1998 if (Pattern == Instance) return true;
1999 Instance = Instance->getInstantiatedFromMemberTemplate();
2000 } while (Instance);
2001
2002 return false;
2003}
2004
Douglas Gregored9c0f92009-10-29 00:04:11 +00002005static bool
2006isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2007 ClassTemplatePartialSpecializationDecl *Instance) {
2008 Pattern
2009 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2010 do {
2011 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2012 Instance->getCanonicalDecl());
2013 if (Pattern == Instance)
2014 return true;
2015 Instance = Instance->getInstantiatedFromMember();
2016 } while (Instance);
2017
2018 return false;
2019}
2020
John McCall52a575a2009-08-29 08:11:13 +00002021static bool isInstantiationOf(CXXRecordDecl *Pattern,
2022 CXXRecordDecl *Instance) {
2023 Pattern = Pattern->getCanonicalDecl();
2024
2025 do {
2026 Instance = Instance->getCanonicalDecl();
2027 if (Pattern == Instance) return true;
2028 Instance = Instance->getInstantiatedFromMemberClass();
2029 } while (Instance);
2030
2031 return false;
2032}
2033
2034static bool isInstantiationOf(FunctionDecl *Pattern,
2035 FunctionDecl *Instance) {
2036 Pattern = Pattern->getCanonicalDecl();
2037
2038 do {
2039 Instance = Instance->getCanonicalDecl();
2040 if (Pattern == Instance) return true;
2041 Instance = Instance->getInstantiatedFromMemberFunction();
2042 } while (Instance);
2043
2044 return false;
2045}
2046
2047static bool isInstantiationOf(EnumDecl *Pattern,
2048 EnumDecl *Instance) {
2049 Pattern = Pattern->getCanonicalDecl();
2050
2051 do {
2052 Instance = Instance->getCanonicalDecl();
2053 if (Pattern == Instance) return true;
2054 Instance = Instance->getInstantiatedFromMemberEnum();
2055 } while (Instance);
2056
2057 return false;
2058}
2059
John McCalled976492009-12-04 22:46:56 +00002060static bool isInstantiationOf(UsingShadowDecl *Pattern,
2061 UsingShadowDecl *Instance,
2062 ASTContext &C) {
2063 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2064}
2065
2066static bool isInstantiationOf(UsingDecl *Pattern,
2067 UsingDecl *Instance,
2068 ASTContext &C) {
2069 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2070}
2071
John McCall7ba107a2009-11-18 02:36:19 +00002072static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2073 UsingDecl *Instance,
2074 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002075 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002076}
2077
2078static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002079 UsingDecl *Instance,
2080 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002081 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002082}
2083
John McCall52a575a2009-08-29 08:11:13 +00002084static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2085 VarDecl *Instance) {
2086 assert(Instance->isStaticDataMember());
2087
2088 Pattern = Pattern->getCanonicalDecl();
2089
2090 do {
2091 Instance = Instance->getCanonicalDecl();
2092 if (Pattern == Instance) return true;
2093 Instance = Instance->getInstantiatedFromStaticDataMember();
2094 } while (Instance);
2095
2096 return false;
2097}
2098
John McCalled976492009-12-04 22:46:56 +00002099// Other is the prospective instantiation
2100// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002101static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002102 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002103 if (UnresolvedUsingTypenameDecl *UUD
2104 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2105 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2106 return isInstantiationOf(UUD, UD, Ctx);
2107 }
2108 }
2109
2110 if (UnresolvedUsingValueDecl *UUD
2111 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002112 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2113 return isInstantiationOf(UUD, UD, Ctx);
2114 }
2115 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002116
Anders Carlsson0d8df782009-08-29 19:37:28 +00002117 return false;
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
John McCall52a575a2009-08-29 08:11:13 +00002120 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2121 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002122
John McCall52a575a2009-08-29 08:11:13 +00002123 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2124 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002125
John McCall52a575a2009-08-29 08:11:13 +00002126 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2127 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002128
Douglas Gregor7caa6822009-07-24 20:34:43 +00002129 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002130 if (Var->isStaticDataMember())
2131 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2132
2133 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2134 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002135
Douglas Gregor0d696532009-09-28 06:34:35 +00002136 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2137 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2138
Douglas Gregored9c0f92009-10-29 00:04:11 +00002139 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2140 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2141 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2142 PartialSpec);
2143
Anders Carlssond8b285f2009-09-01 04:26:58 +00002144 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2145 if (!Field->getDeclName()) {
2146 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002147 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002148 cast<FieldDecl>(D);
2149 }
2150 }
Mike Stump1eb44332009-09-09 15:08:12 +00002151
John McCalled976492009-12-04 22:46:56 +00002152 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2153 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2154
2155 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2156 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2157
Douglas Gregor815215d2009-05-27 05:35:12 +00002158 return D->getDeclName() && isa<NamedDecl>(Other) &&
2159 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2160}
2161
2162template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002163static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002164 NamedDecl *D,
2165 ForwardIterator first,
2166 ForwardIterator last) {
2167 for (; first != last; ++first)
2168 if (isInstantiationOf(Ctx, D, *first))
2169 return cast<NamedDecl>(*first);
2170
2171 return 0;
2172}
2173
John McCall02cace72009-08-28 07:59:38 +00002174/// \brief Finds the instantiation of the given declaration context
2175/// within the current instantiation.
2176///
2177/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002178DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002179 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002180 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002181 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002182 return cast_or_null<DeclContext>(ID);
2183 } else return DC;
2184}
2185
Douglas Gregored961e72009-05-27 17:54:46 +00002186/// \brief Find the instantiation of the given declaration within the
2187/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002188///
2189/// This routine is intended to be used when \p D is a declaration
2190/// referenced from within a template, that needs to mapped into the
2191/// corresponding declaration within an instantiation. For example,
2192/// given:
2193///
2194/// \code
2195/// template<typename T>
2196/// struct X {
2197/// enum Kind {
2198/// KnownValue = sizeof(T)
2199/// };
2200///
2201/// bool getKind() const { return KnownValue; }
2202/// };
2203///
2204/// template struct X<int>;
2205/// \endcode
2206///
2207/// In the instantiation of X<int>::getKind(), we need to map the
2208/// EnumConstantDecl for KnownValue (which refers to
2209/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002210/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2211/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002212NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002213 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002214 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002215 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002216 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002217 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002218 // D is a local of some kind. Look into the map of local
2219 // declarations to their instantiations.
2220 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2221 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002222
Douglas Gregore95b4092009-09-16 18:34:49 +00002223 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2224 if (!Record->isDependentContext())
2225 return D;
2226
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002227 // If the RecordDecl is actually the injected-class-name or a
2228 // "templated" declaration for a class template, class template
2229 // partial specialization, or a member class of a class template,
2230 // substitute into the injected-class-name of the class template
2231 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002232 QualType T;
2233 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2234
2235 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002236 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002237 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2238 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002239 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002240
2241 // If we call SubstType with an InjectedClassNameType here we
2242 // can end up in an infinite loop.
2243 T = Context.getTypeDeclType(Record);
2244 assert(isa<InjectedClassNameType>(T) &&
2245 "type of partial specialization is not an InjectedClassNameType");
2246 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2247 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002248
2249 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002250 // Substitute into the injected-class-name to get the type
2251 // corresponding to the instantiation we want, which may also be
2252 // the current instantiation (if we're in a template
2253 // definition). This substitution should never fail, since we
2254 // know we can instantiate the injected-class-name or we
2255 // wouldn't have gotten to the injected-class-name!
2256
2257 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2258 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002259 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2260 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2261
2262 if (!T->isDependentType()) {
2263 assert(T->isRecordType() && "Instantiation must produce a record type");
2264 return T->getAs<RecordType>()->getDecl();
2265 }
2266
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002267 // We are performing "partial" template instantiation to create
2268 // the member declarations for the members of a class template
2269 // specialization. Therefore, D is actually referring to something
2270 // in the current instantiation. Look through the current
2271 // context, which contains actual instantiations, to find the
2272 // instantiation of the "current instantiation" that D refers
2273 // to.
2274 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002275 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002276 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002277 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002278 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002279 if (isInstantiationOf(ClassTemplate,
2280 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002281 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002282
2283 if (!DC->isDependentContext())
2284 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002285 }
2286
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002287 // We're performing "instantiation" of a member of the current
2288 // instantiation while we are type-checking the
2289 // definition. Compute the declaration context and return that.
2290 assert(!SawNonDependentContext &&
2291 "No dependent context while instantiating record");
2292 DeclContext *DC = computeDeclContext(T);
2293 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002294 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002295 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002296 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002297
Douglas Gregore95b4092009-09-16 18:34:49 +00002298 // Fall through to deal with other dependent record types (e.g.,
2299 // anonymous unions in class templates).
2300 }
John McCall52a575a2009-08-29 08:11:13 +00002301
Douglas Gregore95b4092009-09-16 18:34:49 +00002302 if (!ParentDC->isDependentContext())
2303 return D;
2304
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002305 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002306 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002307 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor815215d2009-05-27 05:35:12 +00002309 if (ParentDC != D->getDeclContext()) {
2310 // We performed some kind of instantiation in the parent context,
2311 // so now we need to look into the instantiated parent context to
2312 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002313
John McCall3cb0ebd2010-03-10 03:28:59 +00002314 // If our context used to be dependent, we may need to instantiate
2315 // it before performing lookup into that context.
2316 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002317 if (!Spec->isDependentContext()) {
2318 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002319 const RecordType *Tag = T->getAs<RecordType>();
2320 assert(Tag && "type of non-dependent record is not a RecordType");
2321 if (!Tag->isBeingDefined() &&
2322 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2323 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002324 }
2325 }
2326
Douglas Gregor815215d2009-05-27 05:35:12 +00002327 NamedDecl *Result = 0;
2328 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002329 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002330 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2331 } else {
2332 // Since we don't have a name for the entity we're looking for,
2333 // our only option is to walk through all of the declarations to
2334 // find that name. This will occur in a few cases:
2335 //
2336 // - anonymous struct/union within a template
2337 // - unnamed class/struct/union/enum within a template
2338 //
2339 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002340 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002341 ParentDC->decls_begin(),
2342 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002343 }
Mike Stump1eb44332009-09-09 15:08:12 +00002344
John McCall9f54ad42009-12-10 09:41:52 +00002345 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002346 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2347 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002348 && "Unable to find instantiation of declaration!");
2349
Douglas Gregor815215d2009-05-27 05:35:12 +00002350 D = Result;
2351 }
2352
Douglas Gregor815215d2009-05-27 05:35:12 +00002353 return D;
2354}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002355
Mike Stump1eb44332009-09-09 15:08:12 +00002356/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002357/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002358void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2359 while (!PendingLocalImplicitInstantiations.empty() ||
2360 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2361 PendingImplicitInstantiation Inst;
2362
2363 if (PendingLocalImplicitInstantiations.empty()) {
2364 Inst = PendingImplicitInstantiations.front();
2365 PendingImplicitInstantiations.pop_front();
2366 } else {
2367 Inst = PendingLocalImplicitInstantiations.front();
2368 PendingLocalImplicitInstantiations.pop_front();
2369 }
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregor7caa6822009-07-24 20:34:43 +00002371 // Instantiate function definitions
2372 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002373 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002374 Function->getLocation(), *this,
2375 Context.getSourceManager(),
2376 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002378 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002379 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002380 continue;
2381 }
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Douglas Gregor7caa6822009-07-24 20:34:43 +00002383 // Instantiate static data member definitions.
2384 VarDecl *Var = cast<VarDecl>(Inst.first);
2385 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002386
Chandler Carruth291b4412010-02-13 10:17:50 +00002387 // Don't try to instantiate declarations if the most recent redeclaration
2388 // is invalid.
2389 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2390 continue;
2391
2392 // Check if the most recent declaration has changed the specialization kind
2393 // and removed the need for implicit instantiation.
2394 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2395 case TSK_Undeclared:
2396 assert(false && "Cannot instantitiate an undeclared specialization.");
2397 case TSK_ExplicitInstantiationDeclaration:
2398 case TSK_ExplicitInstantiationDefinition:
2399 case TSK_ExplicitSpecialization:
2400 continue; // No longer need implicit instantiation.
2401 case TSK_ImplicitInstantiation:
2402 break;
2403 }
2404
Mike Stump1eb44332009-09-09 15:08:12 +00002405 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002406 Var->getLocation(), *this,
2407 Context.getSourceManager(),
2408 "instantiating static data member "
2409 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Douglas Gregor7caa6822009-07-24 20:34:43 +00002411 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002412 }
2413}